C# accessing protected member in derived class [duplicate]

浪子不回头ぞ 提交于 2019-11-29 13:37:28

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);
    }
}

There is no relationship, and it sounds like you are confused why that field is not public.

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

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

Because B has inherited the data from A in this instance.

You could do

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

In your code, you're trying to access Howdy from outside an A, not from within a B. Here, you are inside a B, and can therefore access the protected member in A.

A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type.

You are getting error because because A is not derived from B.

http://msdn.microsoft.com/en-us/library/bcd5672a(v=vs.90).aspx

A protected member is only visible to itself and derived members. In your case, the declaration of A implies that only public members are accessible, just as if you instantiated an A from any other class. You could, however, simply write this.Howdy, because, due to the derivation chain, Howdy is available from inside of class B.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!