有没有办法从派生类型到达另一个对象的“受保护"成员? [英] Is there a way to reach a `protected` member of another object from a derived type?

查看:27
本文介绍了有没有办法从派生类型到达另一个对象的“受保护"成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

推荐答案

不,你不能这样做.

您只能访问访问类型(或派生自它)的对象的受保护成员.在这里,我们不知道参数的类型是 MyType 还是 SomeOtherCompletelyDifferentType.

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.

C# 3.0 规范的相关部分是第 3.5.3 节:

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.

这篇关于有没有办法从派生类型到达另一个对象的“受保护"成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆