简体   繁体   中英

Trying to access protected member in derived class using base class object

This line gives error: Cannot access protected member BaseClass.number via a qualifier of type BaseClass ,the qualifier must be of type DerivedClass (or derived from it) can someone help me with this . see the code below thanks in adavance

using System;
public class BaseClass
{
    protected int number = 10;
}
public class DerivedClass: BaseClass
{   
    public void Print()
    {
        BaseClass obj = new BaseClass();
        //Console.WriteLine(obj.number); 
    // we get error if we try to print why?
    }
}
class Program
{
    public static void Main()
    {
        DerivedClass obj2 = new DerivedClass();
        obj2.Print();
    }
}

but why does compiler gives error. why this way of calling method is wrong

Your question seems to mirror this example in the docs.

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

public class DerivedClass : BaseClass
{   
    public void Print()
    {
        BaseClass baseClass = new BaseClass();
        DerivedClass derived = new DerivedClass();

        // This is ok
        Console.WriteLine(number); 

        // So is this
        Console.WriteLine(derived.number);

        // But you can't do this
        Console.WriteLine(baseClass.number); 
    }
}

Without this restriction in place the following would be possible, which is clearly a security flaw:

public class AnotherDerivedClass : BaseClass
{
    public bool IsValid => number == 10;
}

public class DerivedClass : BaseClass
{   
    public void Print()
    {
        BaseClass anotherAsBase = new AnotherDerivedClass();

        anotherAsBase.number = 0;
    }
}

In the above example, an instance of DerivedClass has interfered with the implementation details of AnotherDerivedClass . As DerivedClass is a completely different type to AnotherDerivedClass , it shouldn't be able to do this.

using System;
public class BaseClass
{
    protected int number = 10;
}
public class DerivedClass : BaseClass
{
    public void Print()
    {
        this.number = 20;  // you access it as a private filed 

    }
}
class Program
{
    public static void Main()
    {
        DerivedClass obj2 = new DerivedClass();
        obj2.Print();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM