4

.NET 中的“受保护”和“受保护的内部”修饰符有什么区别?

4

4 回答 4

10

私人的

仅允许从特定类型内访问

受保护

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

内部的

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

所以它遵循:

受保护的内部

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

基本上,首先将所有内容视为private第一,然后将其他任何您视为扩展的内容都考虑在内。

于 2009-05-20T17:14:08.687 回答
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() { }
}
于 2009-05-20T16:55:35.213 回答
2

像往常一样,来自Fabulous Eric Lippert 的一篇博文:

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

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

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

于 2009-05-20T20:32:52.030 回答
1

protected对于和lemme之间的区别,请protected internal举一个简短的例子,我将匹配这个例子......

Country A: 一个组件

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

XY(基类)是A 国(继承类)的父亲

Z(Inherited Class of ) 是B 国X的另一个儿子。X

X有财产。

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

  2. 如果X提到财产,protected internal那么 说:包括我儿子在内X的我国家的所有人,都可以访问我的财产。亲爱的儿子,你仍然可以访问我的财产。AYZCountry B

希望大家明白...

谢谢你。

于 2010-11-04T16:23:36.037 回答