c# - 如果我声明一个内部类,内部成员的默认访问级别是什么?

标签 c# member internal access-modifiers

我正在构建一个具有一些基本功能的 DLL。长话短说,我正在制作一些供开发人员使用的静态类。这些类使用一些其他类来完成肮脏的工作,我将其标记为内部类,因为我不希望人们访问它们。

问题是:如果我将一个类声明为内部类,他的成员的访问级别是什么?

我必须将其所有成员标记为内部成员,还是它们也会自动标记为内部成员?

我在 stackoverflow 上谷歌搜索和搜索已经用了 2 个小时,我正在努力寻找一个清晰直接的答案,其中不包括 1000 种推测、技术上不太可能的假设和无用的装饰...

MSDN 一如既往的困惑(从未在 msdn 上找到明确的答案)。

从我在这里可以读到的http://msdn.microsoft.com/en-us/library/ms173121.aspx我猜想无论你如何设置一个类的访问级别,他的所有成员都是私有(private)的(方法、变量等)。

求助,我不知道

最佳答案

The question is: If I declare a class as internal, what the access level of his members will be?

默认为私有(private)。如果还有什么,那就看情况了。如果它们不是公共(public)的,则访问修饰符将按照 MSDN 中的描述应用(例如,在程序集外不可见)。

但是,在您发布的链接中,有一个适用于非静态类的陷阱:

Normally, the accessibility of a member is not greater than the accessibility of the type that contains it. However, a public member of an internal class might be accessible from outside the assembly if the member implements interface methods or overrides virtual methods that are defined in a public base class.


关于上一段,既然静态类不能实现接口(interface),也不能继承其他类那你大可放心。只要您将静态类声明为内部类,成员就不会在其他程序集中可用(除非您的开发人员使用反射)。

举例说明它是如何为非静态类工作的:

程序集 1

public interface ISomePublicInterface
{
    int GetValue();
}

internal class InternalClass : ISomePublicInterface
{
    public int GetValue()
    {
        return 100;
    }
}

public static class SomeFactory
{
    public static ISomePublicInterface GetInternalInstanceAsInterface()
    {
        return new InternalClass();
    }
}

程序集 2

ISomePublicInterface val = SomeFactory.GetInternalInstanceAsInterface();
Console.WriteLine(val.GetValue()); //-->> Calls public method in internal class
Console.WriteLine(val.GetType());

猜猜输出是什么?

Assembly1.InternalClass

因此,现在您可以访问程序集外部的类型,并且可以通过反射调用其他内部方法(这不是获取它的唯一方法)。

关于c# - 如果我声明一个内部类,内部成员的默认访问级别是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25217014/

相关文章:

c# - 将 IdentityUser 与 OAuth 结合使用时,“对象”不包含 'Action' 的定义

c# - naudio 从麦克风录制声音然后保存

c++ - 使用对象或指向对象的指针作为类成员和内存分配

android:查找是否存在 sd 卡

c# - 使用 DataTable.Load() 而不创建所有列属性

c# - 等价于 C# 的 C++ typedef 结构

function - C++ : using class member and static function of same name but different parameters fails

c- 在函数中分配结构成员时出错

c# - 绑定(bind)到内部 ViewModel-Property

iis - VS Express 2013 for Web : How to use the internal VS server, 不是 IIS express?