我有以下结构:
abstract class Parent {}
class Child : Parent
{
// Member Variable that I want access to:
OleDbCommand[] _commandCollection;
// Auto-generated code here
}
是否可以在 Parent 类中使用反射来访问 Child 类中的 _commandCollection?如果没有任何关于我如何实现这一目标的建议?
编辑: 可能值得一提的是,在抽象父类中,我计划使用 IDbCommand[] 来处理 _commandCollection 对象,因为并非我所有的 TableAdapter 都将使用 OleDb 连接到它们各自的数据库。
编辑 2: 对于所有评论说...只是向子类添加一个函数属性,我不能因为它是由 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);
数组协变应确保转换成功。
我假设某些设计师会生成子类?否则,您可能正在寻找 protected 属性(property)。
关于c#使用反射从派生类中获取私有(private)成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4097682/