.NET中,“protected”和“protected internal”修饰符有什么区别?
私有的
只允许在特定类型内部访问
受保护的
私有访问被扩展到包括继承类型
内部的
私有访问被扩展到包括同一程序集中的其他类型
因此,可以得出以下结论:
受保护的内部的
私有访问被扩展为允许访问这个类型继承自或与该类型位于同一程序集中的类型,或者两者皆满足。
基本上,可以将所有内容视为首先是private
,而其他任何看到的内容都是在此基础上进行扩展。
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() { }
}
protected internal
] 意味着 "M对于所有位于此程序集中的派生类都是可访问的。" 但实际上并非如此。它实际上意味着"M对于所有派生类和此程序集中的所有类都是可访问的"。也就是说,它是较不严格的组合,而不是更严格的组合。internal
、protected
和private
看作是从public
的“自然”状态中受到限制。按照这种模型,protected internal
的含义是“应用受保护的限制和内部限制”。internal
、protected
和public
是private
的弱化形式。在C#中,private
是默认值;如果希望某些内容具有更广泛的可访问性,则必须明确说明。按照这种模型,那么就很清楚,protected internal
是比单独使用任何一个限制都要弱的限制。关于protected
和protected internal
之间的区别,让我举一个简单的例子,并将其与现实生活中的情况进行匹配...
国家A
: 一个程序集
国家B
: 另一个不同的程序集
X
(基类)是Y
(派生类)在国家A中的父亲
Z
(X
的派生类)是在国家B中的另一个儿子。
X
有一个属性。
如果 X
将属性标记为 protected
,那么
X
说:我的所有儿子 Y
和 Z
,只有你们两个无论身在何处都可以访问我的属性...上帝保佑你们。除了你们,没有人能够访问我的属性。
如果 X
将属性标记为 protected internal
,那么
X
说:我国家的所有人,包括我的儿子 Y
,都可以访问我的属性。亲爱的儿子 Z
,你仍然可以在 B 国
访问我的属性。
希望大家都明白了...
谢谢。