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

时间:2009-05-20 16:53:56

标签: .net access-modifiers

.NET中“protected”和“protected internal”修饰符有什么区别?

4 个答案:

答案 0 :(得分:10)

<强>私有

  

只允许从特定类型

中访问

<强>保护

  

私有访问权限已扩展为包含继承类型

<强>内部

  

私有访问权限已扩展为包含同一程序集中的其他类型

因此:

受保护的内部

  

私有访问权限已扩展为允许访问 继承的类型或与此类型相同的程序集,或两者兼而有之。

基本上,首先将所有内容都视为private,并将其他任何内容视为扩展内容。

答案 1 :(得分: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() { }
}

答案 2 :(得分:2)

像往常一样,来自Fabulous Eric Lippert's blog posts之一:

  

许多人认为[protected internal]意味着“M可以访问此程序集中的所有派生类。”它没有。 它实际上意味着“M可以被所有派生类和此程序集中的所有类访问”也就是说,它是限制较少的组合,而不是更严格的组合。

     

这对许多人来说都是违反直觉的。我一直想弄清楚为什么,我想我已经明白了。我认为人们认为internalprotectedprivatepublic的“自然”状态的限制。使用该模型,protected internal表示“同时应用受保护的限制和内部限制”。

     

这是错误的思考方式。相反,internalprotectedpublicprivate的“自然”状态的弱化。 private是C#中的默认值;如果你想让某些东西具有更广泛的可访问性,你必须这么说。有了这个模型,很明显protected internal是一个比单独使用更弱的限制。

答案 3 :(得分:1)

protected protected internal 之间的区别给出了一个简短的示例,我将匹配示例......

Country A:一个集会

Country B:另一个不同的集会

X(基类)是国家A中Y(继承类)的父亲

Z(继承类X)是B国X的另一个儿子。

X有一个属性。

  1. 如果X将该属性提及为protected,那么        X说:我所有的儿子YZ,只有你们两个都能在我住的地方进入我的财产......上帝保佑你们。除了你,没有人可以访问我的财产。

  2. 如果X将该属性提及为protected internal,那么        X说:我国A的所有人,包括我的儿子Y,都可以访问我的财产。亲爱的儿子Z,您仍可以Country B访问我的财产。

  3. 希望你们明白......

    谢谢你。

相关问题