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

我有以下结构:

abstract class Parent {} class Child : Parent { // Member Variable that I want access to: OleDbCommand[] _commandCollection; // Auto-generated code here } 

是否可以使用Parent类中的reflection来访问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 GetCommands();