C# accessing protected member in derived class [du

2019-01-27 18:46发布

问题:

This question already has an answer here:

  • Why can't I access C# protected members except like this? 6 answers

I wrote the following code:

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

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

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

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

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?

So, why does this happen?


Found a strict answer - http://blogs.msdn.com/b/ericlippert/archive/2005/11/09/491031.aspx

回答1:

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.



回答2:

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.



回答3:

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



回答4:

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.