.NET 中的“受保护”和“受保护的内部”修饰符有什么区别?
4 回答
私人的
仅允许从特定类型内访问
受保护
私有访问被扩展为包括继承类型
内部的
私有访问被扩展为在同一程序集中包含其他类型
所以它遵循:
受保护的内部
私有访问被扩展为允许访问继承自此类型或与此类型位于同一程序集中的类型,或两者兼而有之。
基本上,首先将所有内容视为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() { }
}
像往常一样,来自Fabulous Eric Lippert 的一篇博文:
许多人认为 [
protected internal
] 表示“此程序集中的所有派生类都可以访问 M”。它不是。它实际上意味着“所有派生类和此程序集中的所有类都可以访问 M”。 也就是说,它是限制较少的组合,而不是限制较多的组合。这对很多人来说是违反直觉的。我一直试图找出原因,我想我明白了。我认为人们将
internal
,protected
和private
视为 . 的“自然”状态的限制public
。使用该模型,protected internal
意味着“同时应用受保护的限制和内部限制”。这是错误的思考方式。相反,
internal
和protected
是public
的“自然”状态的弱化private
。private
是 C# 中的默认值;如果你想让某些东西具有更广泛的可访问性,你必须这么说。使用该模型,很明显它protected internal
的限制比单独的任何一个都弱。
protected
对于和lemme之间的区别,请protected internal
举一个简短的例子,我将匹配这个例子......
Country A
: 一个组件
Country B
: 另一个不同的程序集
X
Y
(基类)是A 国(继承类)的父亲
Z
(Inherited Class of ) 是B 国X
的另一个儿子。X
X
有财产。
如果
X
提到财产,protected
然后X
说:我所有的儿子Y
和Z
,只有你们俩可以在任何地方访问我的财产……上帝保佑你。除了你,没有人可以访问我的财产。如果
X
提到财产,protected internal
那么 说:包括我儿子在内X
的我国家的所有人,都可以访问我的财产。亲爱的儿子,你仍然可以访问我的财产。A
Y
Z
Country B
希望大家明白...
谢谢你。