Is there a way to reach a `protected` member of another object from a derived type?

后端 未结 7 1141
轻奢々
轻奢々 2020-11-30 13:41
class MyBase
{
    protected object PropertyOfBase { get; set; }
}

class MyType : MyBase
{
    void MyMethod(MyBase parameter)
    {
        // I am looking for:
           


        
7条回答
  •  眼角桃花
    2020-11-30 14:16

    No, you can't do this.

    You're only allowed to access protected members of objects of the accessing type (or derived from it). Here, we don't know whether the parameter is of type MyType or SomeOtherCompletelyDifferentType.

    EDIT: The relevant bit of the C# 3.0 spec is section 3.5.3:

    When a protected instance member is accessed outside the program text of the class in which it is declared, and when a protected internal instance member is accessed outside the program text of the program in which it is declared, the access must take place within a class declaration that derives from the class in which it is declared. Furthermore, the access is required to take place through an instance of that derived class type or a class type constructed from it. This restriction prevents one derived class from accessing protected members of other derived classes, even when the members are inherited from the same base class.

提交回复
热议问题