通过基类变量访问 C# 受保护成员
这可能看起来相当新手问题,但你能解释一下为什么方法 Der.B() 无法通过基类变量访问受保护的 Foo 吗?这对我来说看起来很奇怪:
public class Base
{
protected int Foo;
}
public class Der : Base
{
private void B(Base b) { Foo = b.Foo; } // Error: Cannot access protected member
private void D(Der d) { Foo = d.Foo; } // OK
}
谢谢!
It may seems rather newbie question, but can you explain why method Der.B() cannot access protected Foo via Base class variable? This looks weird to me:
public class Base
{
protected int Foo;
}
public class Der : Base
{
private void B(Base b) { Foo = b.Foo; } // Error: Cannot access protected member
private void D(Der d) { Foo = d.Foo; } // OK
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个常见问题。要弄清楚为什么这是非法的,请考虑一下可能会出现什么问题。
假设您有另一个从 Base 派生的派生类 Flob。现在您将 Frob 的一个实例传递给 Der.B。您应该能够从 Der.B 访问 Frob.Foo 吗?不,绝对不是。 Frobe.Foo 受到保护;它应该只能从 Frob 和 Frob 的子类访问。 Der 不是 Frob,也不是 Frob 的子类,因此它无法访问 Frob 的受保护成员。
如果不清楚,请参阅我关于该主题的文章:
http:// /blogs.msdn.com/ericlippert/archive/2005/11/09/491031.aspx
This is a frequently asked question. To figure out why this is illegal, think about what could go wrong.
Suppose you had another derived class Frob derived from Base. Now you pass an instance of Frob to Der.B. Should you be able to access Frob.Foo from Der.B? No, absolutely not. Frob.Foo is protected; it should only be accessible from Frob and subclasses of Frob. Der is not Frob and is not a subclass of Frob, so it does not get access to Frob's protected members.
If that's not clear, see my article on the subject:
http://blogs.msdn.com/ericlippert/archive/2005/11/09/491031.aspx
在 B 中,您正尝试访问另一个类的受保护成员。您从该类继承的事实是无关紧要的。在 D 中,您正在访问当前类的基类的受保护成员。在此上下文中,您可以访问 Der 中的任何内容以及它所继承的类型的受保护成员。
In B you are trying to access a protected member of another class. The fact that you are inheriting from that class is irrelevant. In D you are accessing a protected member of the base class of your current class. In this context you can access anything from Der and the protected members of the type it is inheriting from.
您可以通过在基类中声明静态方法来解决此限制:
You can work around this limitation by declaring a static method in the base class:
简单地说,protected 允许访问子类。
在:
您正在尝试访问您的 Der 实例无权访问的受保护成员。只有当它是当前 Der 实例(this)的基类时,它才可以访问它。
工作正常,因为您正在通过 Der 访问它的基类受保护方法。
Simply put, protected allows access to sub classes.
In:
You are attempting to access a protected member your instance of Der doesn't have access to. It would only have access to it if it was the base class of your current instance of Der (this).
Works fine because you are going through Der to access it's Base classes protected method.
在您尝试的场景中,您将需要对 int Foo 使用“internal”。
In the scenario you're trying you'll want to use "internal" for int Foo.