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

c#使用反射从派生类获取私有成员变量,c#,reflection,inheritance,C#,Reflection,Inheritance,我的结构如下: abstract class Parent {} class Child : Parent { // Member Variable that I want access to: OleDbCommand[] _commandCollection; // Auto-generated code here } 是否可以使用父类中的反射来访问子类中的_commandCollection?如果没有任何关于如何实现这一目标的建议 编辑: 可能值得一提

我的结构如下:

abstract class Parent {}


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

    // Auto-generated code here
}
是否可以使用父类中的反射来访问子类中的_commandCollection?如果没有任何关于如何实现这一目标的建议

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

EDIT2: 对于所有的评论说。。。只需将function的属性添加到子类中,我无法将其作为VS设计器自动生成的属性。我真的不想每次我在设计中改变一些东西时都要重新做我的工作

// _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();
受保护的抽象IEnumerable GetCommands();

wow。这是一种很重的代码味道。为什么不将
\u commandCollection
放在父项中,并将其键入
IDbCommand[]
?然后你得到了你想要的,你只需要在子类中进行转换。@TK我建议你检查一下你的代码架构。如果缺少controller class.TK,就会出现这种情况-我可以说明您的问题。MS习惯于在生成的代码中设置私有的、真正需要从派生类访问的内容。我将用它来做类似的事情。作为一个需要非自有类解决方案的例子,微软有很多私有成员,它们本应该可以扩展。当设计被破坏时,访问“私有”的东西是一种真实而实际的需要。我意识到在大多数情况下,私有真正的意思是“放手不要碰”,但在这种情况下,我试图有一个单一的解决方案,允许我的所有(100+)表适配器使用这段通用代码,而不是创建和维护100+部分类。