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

TK.*_*TK. 3 c# reflection inheritance

我有以下结构:

abstract class Parent {}


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

    // Auto-generated code here
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Ani*_*Ani 9

// _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);
Run Code Online (Sandbox Code Playgroud)

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

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