受保护的内部成员(C# 参考)protected internal (C# Reference)

protected internal 关键字组合是一种成员访问修饰符。The protected internal keyword combination is a member access modifier. 可从当前程序集或派生自包含类的类型访问受保护的内部成员。A protected internal member is accessible from the current assembly or from types that are derived from the containing class. 有关 protected internal 和其他访问修饰符的比较,请参阅可访问性级别For a comparison of protected internal with the other access modifiers, see Accessibility Levels.

示例Example

可从包含程序集内的任何类型访问基类的受保护的内部成员。A protected internal member of a base class is accessible from any type within its containing assembly. 也可在另一程序集中的派生类中访问它,前提是通过派生类类型的变量进行访问。It is also accessible in a derived class located in another assembly only if the access occurs through a variable of the derived class type. 以下面的代码段为例:For example, consider the following code segment:

// Assembly1.cs
// Compile with: /target:library
public class BaseClass
{
   protected internal int myValue = 0;
}

class TestAccess
{
    void Access()
    {
        var baseObject = new BaseClass();
        baseObject.myValue = 5;
    }
}
// Assembly2.cs
// Compile with: /reference:Assembly1.dll
class DerivedClass : BaseClass
{
    static void Main()
    {
        var baseObject = new BaseClass();
        var derivedObject = new DerivedClass();

        // Error CS1540, because myValue can only be accessed by
        // classes derived from BaseClass.
        // baseObject.myValue = 10;

        // OK, because this class derives from BaseClass.
        derivedObject.myValue = 10;
    }
}

此示例包含两个文件,即 Assembly1.csAssembly2.csThis example contains two files, Assembly1.cs and Assembly2.cs. 第一个文件包含公共基类 BaseClass 和另一个类 TestAccessThe first file contains a public base class, BaseClass, and another class, TestAccess. BaseClass 拥有受保护的内部成员 myValue,由 TestAccess 类型访问。BaseClass owns a protected internal member, myValue, which is accessed by the TestAccess type. 在第二个文件中,如果尝试通过 BaseClass 的实例访问 myValue ,会生成错误,但如果尝试通过一个派生类的实例来访问此成员,DerivedClass 会成功。In the second file, an attempt to access myValue through an instance of BaseClass will produce an error, while an access to this member through an instance of a derived class, DerivedClass will succeed.

结构成员不能为 protected internal,因为无法继承结构。Struct members cannot be protected internal because the struct cannot be inherited.

C# 语言规范C# language specification

有关详细信息,请参阅 C# 语言规范For more information, see the C# Language Specification. 该语言规范是 C# 语法和用法的权威资料。The language specification is the definitive source for C# syntax and usage.

请参阅See also