.NET中的"protected"和"protected internal"修饰符有什么区别?

Bha*_*kar 4 .net access-modifiers

.NET中的"protected"和"protected internal"修饰符有什么区别?

Joe*_*orn 10

私人的

只允许从特定类型中访问

保护

私有访问被扩展为包括继承类型

内部

私有访问被扩展为包括同一程序集中的其他类型

所以它遵循:

保护内部

私有访问被扩展以允许类型的存取要么从继承或在同一个组件,这种类型的,或两者.

基本上,首先要考虑所有事情private,并将其他任何事情视为扩展.


And*_*are 7

protected

成员仅对继承类型可见.

protected internal

成员仅对继承类型以及与声明类型包含在同一程序集中的所有类型可见.

这是一个C#示例:

class Program
{
    static void Main()
    {
        Foo foo = new Foo();

        // Notice I can call this method here because
        // the Foo type is within the same assembly
        // and the method is marked as "protected internal".
        foo.ProtectedInternalMethod();

        // The line below does not compile because
        // I cannot access a "protected" method.
        foo.ProtectedMethod();
    }
}

class Foo
{
    // This method is only visible to any type 
    // that inherits from "Foo"
    protected void ProtectedMethod() { }

    // This method is visible to any type that inherits
    // from "Foo" as well as all other types compiled in
    // this assembly (notably "Program" above).
    protected internal void ProtectedInternalMethod() { }
}
Run Code Online (Sandbox Code Playgroud)

  • 确实.它是受保护的或内部的,与它在第一个地方看起来相反+1 (4认同)