C#protected成员通过基类的变量访问 [英] C# protected members accessed via base class variable

查看:291
本文介绍了C#protected成员通过基类的变量访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能看起来相当新手的问题,但你能解释一下为什么法Der.B()不能访问通过基类变量所保护的富?这看起来奇怪的对我说:

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!

推荐答案

这是一个经常被问到的问题。为了弄清楚为什么这是非法的,想想可能出错。

This is a frequently asked question. To figure out why this is illegal, think about what could go wrong.

假设你有另外的派生类FROB从基础的。现在,你通过FROB的实例Der.B.如果你能够从Der.B访问Frob.Foo?不,绝对不是。 Frob.Foo保护;它应该只从FROB和FROB的子类访问。明镜不FROB并且不是FROB的一个子类,因此它没有得到访问FROB的保护成员。

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

这篇关于C#protected成员通过基类的变量访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆