Is there a way to reach a `protected` member of an

2020-01-27 08:09发布

class MyBase
{
    protected object PropertyOfBase { get; set; }
}

class MyType : MyBase
{
    void MyMethod(MyBase parameter)
    {
        // I am looking for:
        object p = parameter.PropertyOfBase;  // error CS1540: Cannot access protected member 'MyBase.PropertyOfBase' via a qualifier of type 'MyBase'; the qualifier must be of type 'MyType' (or derived from it)
    }
}

Is there a way to get a protected property of a parameter of a type from an extending type without reflection? Since the extending class knows of the property through its base type, it would make sense if possible.

标签: c# oop
7条回答
▲ chillily
2楼-- · 2020-01-27 09:03

You can also declare MyType as a nested class of MyBase (instead of inheriting), this way you can access private/protected members when you send the class MyBase as a parameter

public class MyBase
{
    protected object PropertyOfBase { get; set; }

    public class MyType
    {
        public void MyMethod(MyBase parameter)
        {
            object p = parameter.PropertyOfBase;  
        }
    }
}

To create an instance of MyType just use

var t = new MyBase.MyType();
t.MyMethod(new MyBase());
查看更多
登录 后发表回答