C#访问派生类中的受保护成员 [英] C# accessing protected member in derived class

查看:250
本文介绍了C#访问派生类中的受保护成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下代码:

public class A                             
{
    protected string Howdy = "Howdy!";     
}

public class B : A                           
{
    public void CallHowdy()
    {
        A a = new A();
        Console.WriteLine(a.Howdy);
    }
}

现在,在 VS2010 会导致以下编译错误:

Now, in VS2010 it results in the following compilation error:


无法通过类型的限定符访问受保护的成员'A.a' '一种';

Cannot access protected member 'A.a' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it).

这对我来说似乎很不合逻辑-为什么不能我可以从派生自该类的方法中访问该类实例的 protected 字段?

This seems quite illogical to me - why can't I access the protected field of the class instance from a method of the class, which is derived from it?

所以,为什么会这样

找到了严格的答案- http://blogs.msdn.com/b/ericlippert/archive/ 2005/11/09 / 491031.aspx

推荐答案

您不是从类内部访问它,而是试图访问变量,就好像它是 public 。您不会期望它会被编译,这几乎就是您想要做的:

You're not accessing it from inside the class, you're trying to access the variable as though it were public. You would not expect this to compile, and this is pretty much what you are trying to do:

public class SomethingElse
{
    public void CallHowdy()
    {
        A a = new A();
        Console.WriteLine(a.Howdy);
    }
}

没有关系,听起来你像

现在,如果您想这样做,您可以这样做:

Now, you could do this, if you wanted to:

public class B : A
{
    public void CallHowdy()
    {
        Console.Writeline(Howdy);
    }
}

因为 B 继承了 A 的数据。

这篇关于C#访问派生类中的受保护成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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