编程语言
首页 > 编程语言> > c# – 如果我声明一个内部类,内部成员的默认访问级别是什么?

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

作者:互联网

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

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

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

这是一个很好的2小时我在谷歌搜索和搜索stackoverflow,我很难找到一个明确和直接的答案,其中不包括1000个猜测,技术不太可能的hypotesis和无用的装饰……

MSDN像往常一样令人困惑(从未在msdn上找到明确的答案).

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

救命,我不知道

解决方法:

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

默认为私有.如果有的话,那取决于.如果它们不是公共的,那么访问修饰符适用于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.

关于最后一段,由于静态类无法实现接口或继承其他类,因此您可以放心.只要您将静态类声明为内部,成员就不会在其他程序集中可用(除非您的开发人员使用反射).

举例说明它如何对非静态类起作用:

大会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,access-modifiers,internal,member
来源: https://codeday.me/bug/20190713/1454071.html