繁体   English   中英

c#使用reflection从派生类中获取私有成员变量

[英]c# use reflection to get a private member variable from a derived class

我有以下结构:

abstract class Parent {}


class Child : Parent
{   
    // Member Variable that I want access to:
    OleDbCommand[] _commandCollection;

    // Auto-generated code here
}

是否可以使用Parent类中的反射来访问Child类中的_commandCollection? 如果没有关于如何实现这一点的任何建议?

编辑:可能值得一提的是,在抽象的Parent类中,我计划使用IDbCommand []来处理_commandCollection对象,因为并非所有的TableAdapter都将使用OleDb连接到各自的数据库。

EDIT2:对于所有的评论说...只是向子类添加一个函数的属性,我不能像VS Designer自动生成它。 每当我改变设计师的某些东西时,我真的不想重新做我的工作!

// _commandCollection is an instance, private member
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;

// Retrieve a FieldInfo instance corresponding to the field
FieldInfo field = GetType().GetField("_commandCollection", flags);

// Retrieve the value of the field, and cast as necessary
IDbCommand[] cc =(IDbCommand[])field.GetValue(this);

数组协方差应该确保演员表演成功。

我假设一些设计师会生成子类? 否则,受保护的财产可能就是您正在寻找的。

这是可能的,虽然这是一个非常糟糕的主意。

    var field = GetType().GetField("_commandCollection", BindingFlags.Instance | BindingFlags.NonPublic);

我认为你真正想要做的是为子类提供一种方法,为父类提供所需的数据:

protected abstract IEnumerable<IDBCommand> GetCommands();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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