对访问修饰关键字public, protected, internal and private的说明

时间:2021-10-20 17:34:56

对访问修饰关键字public, protected, internal and private的说明
1.
msdn: Internal types or members are accessible only within files in the same assembly.
只要在同一个assembly中就能访问,而不是命名空间。
如下面的例子,在同一个assembly ClassLibrary2.dll中:
namespace ClassLibrary2
{
    public class Class1
    {
        protected string TestString1 { get; set; }
        internal string TestString2 { get; set; }
        protected internal string TestString3 { get; set; }
    }
}

// 在子命名空间中访问
namespace ClassLibrary2.SubNamespace
{
    public class Class2
    {
        public Class2()
        {
            Class1 c1 = new Class1();
            //c1.TestString1 = "1"; // 'ClassLibrary2.Class1.TestString1' is inaccessible due to its protection level
            c1.TestString2 = "2";
            c1.TestString3 = "3";
        }
    }
}

// 在另一个命名空间中访问
namespace AnotherNamespace
{
    public class Class3
    {
        public Class3()
        {
            ClassLibrary2.Class1 c1 = new ClassLibrary2.Class1();
            //c1.TestString1 = "1"; // 'ClassLibrary2.Class1.TestString1' is inaccessible due to its protection level
            c1.TestString2 = "2";
            c1.TestString3 = "3";
        }
    }
}

2. 
protected表示只能在定义它的类的内部或者它的子类内部访问。
被protected internal两个关键字同时修饰的表示能被子类访问(子类可以在另一个assembly中)或者在同一个assembly中访问。
注意它们上并集,不是交集。
例如有另外一个assembly, ClassLibrary3.dll:
namespace ClassLibrary3
{
    public class A : ClassLibrary2.Class1
    {
        public A()
        {
            this.TestString1 = "1";
            //this.TestString2 = "2";  // cannot see it.
            this.TestString3 = "3";
        }
    }
}

3.
Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these

types is internal. 
如果尝试用private,protected, or protected internal修饰一个Top-level class,例如:
private class A
{
}
会报一个错:Error,Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal

但是可以修饰nested class, 如下,是不报错的。B缺省为internal。
class B
{
     private class B1 { }
     protected class B2 { }
     protected internal class B3 { }
}
nested type的缺省修饰如下:
Members of         Default member accessibility          Allowed declared accessibility of the member

enum                 public                                None
class                    private                              public, protected, internal, protected internal, pirvate
interface            public                                None