【问题标题】:What is the difference between the "protected" and "protected internal" modifiers in .NET?.NET 中的“受保护”和“受保护的内部”修饰符有什么区别?
【发布时间】:2010-10-27 16:58:15
【问题描述】:

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

【问题讨论】:

标签: .net access-modifiers


【解决方案1】:

protectedprotected internal 的区别,我举个简单的例子,我会匹配例子...

Country A:一个程序集

Country B: 另一个不同的程序集

X(Base Class) 是 A 国 Y(Inherited Class) 的父亲

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

X 有一个属性。

  1. 如果X 提到该属性为protected 那么 X 说:我所有的儿子YZ,只有你们俩可以在任何地方访问我的财产……上帝保佑你们。除了你,没有人可以访问我的财产。

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

希望你们理解...

谢谢。

【讨论】:

    【解决方案2】:

    私人

    仅允许从特定类型内访问

    受保护

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

    内部

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

    因此得出这样的结论:

    受保护的内部

    私有访问被扩展为允许访问要么继承自此类型或与此类型在同一程序集中,或两者兼而有之的类型。

    基本上,首先将所有内容都视为private,然后您看到的其他任何内容都会扩展。

    【讨论】:

      【解决方案3】:

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

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

      这对很多人来说是违反直觉的。我一直试图找出原因,我想我明白了。我认为人们将internalprotectedprivate 视为public 的“自然”状态的限制。对于该模型,protected internal 表示“同时应用受保护的限制和内部限制”。

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

      【讨论】:

        【解决方案4】:

        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() { }
        }
        

        【讨论】:

        • 确实如此。它是受保护的或内部的,与它最初的外观相反 +1
        猜你喜欢
        • 2012-06-13
        • 2016-03-08
        • 2019-02-22
        • 2012-01-28
        • 2016-08-22
        • 1970-01-01
        • 2019-07-24
        • 2013-03-05
        相关资源
        最近更新 更多