Sal*_*ris 2 c# access-modifiers
C# 中“受保护”和“私有受保护”访问修饰符有什么区别?有人可以举例说明吗?
提前致谢。
这是关于access 修饰符的。更具体地说:继承和多个程序集。考虑以下:
对于正常情况protected(用 解释private):
class Base
{
private bool X;
protected bool Y;
}
class A : Base
{
public void Foo()
{
X = false; //error: cannot access private member.
Y = true; //can access protected member, but only from classes with `: Base`
}
}
class B
{
public void Foo()
{
A a = new A();
a.X = false; //error: cannot access private member.
a.Y = false; //error: cannot access protected member.
}
}
Run Code Online (Sandbox Code Playgroud)
现在的区别private protected在于它必须位于同一个程序集中才能访问:
所以:
class A : Base
{
public void Foo()
{
X = false; //error: cannot access private member.
Y = true; //can access protected member, but only from classes with `: Base` AND
//they need to be defined in the same assembly as Base
}
}
Run Code Online (Sandbox Code Playgroud)
有效,但仅当 和A都Base在同一程序集/dll/exe 等中编译时才有效。
现在,既然已经清楚了,你什么时候会use真正的private protected?
关于这一点可以说很多。有些人(包括我)会认为使用private protected是一种反模式,因为在我看来它与friend关键字密切相关。我必须说,尽管与 矛盾friend,private protected保持“污垢”孤立,但它仍然是任意行为、逻辑,取决于它定义的位置。
话虽如此,问题仍然是,何时使用它。你可能会惊讶于我准时使用过它一次,而且它非常有帮助。
考虑以下情况:
graphical object系统。....然后我会使用private protected;-)
| 归档时间: |
|
| 查看次数: |
3402 次 |
| 最近记录: |