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

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

问题描述

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.

推荐答案

没有,你不能做到这一点。

No, you can't do this.

你只允许访问访问类型的对象的保护成员(或其衍生)。在这里,我们不知道参数是否是一个类型的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:

在一个受保护的实例成员
  的程序文本之外访问
  在声明它的类,
  当一个受保护的内部实例
  件程序之外访问
  其中是节目的文本
  宣布,访问必须发生
  一类声明内
  从它是类的派生
  声明。此外,该访问是
  通过发生所需
  派生类类型的实例或
  类类型从它建造。这个
  限制prevents一个推导出的类
  访问受保护的成员
  其他派生类,即使当
  部件由相同的继承
  基类。

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.

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

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