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吗?如果没有关于如何实现这一点的任何建议?
Is it possible to use reflection from within the Parent class to access the _commandCollection within the Child class? If not any suggestions on how I can achieve this?
编辑:
它可能值得一提的是在抽象的父类我计划使用IDbCommand []来处理_commandCollection对象,因为我的所有TableAdapter都不会使用OleDb连接到各自的数据库。
Its probably worth mentioning that in the abstract Parent class I plan to use IDbCommand[] to handle the _commandCollection object as not all my TableAdapters will be using OleDb to connect to their respective databases.
EDIT2:
对于所有评论说...只是向子类添加一个函数属性,我不能像VS Designer自动生成它。每次我在设计师中改变某些东西时,我真的不想重新做我的工作!
For all the comments saying ... just add a property of function to the child class, I can't as its automatically generated by the VS Designer. I really don't want to have to re-do my work every time I change something in the 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);
数组协方差应该确保演员表演成功。
Array covariance should ensure that the cast is successful.
我假设一些设计师会生成子类?否则,您可能正在寻找受保护的财产。
I assume some designer will be generating the subclasses? Otherwise, a protected property is probably what you're looking for.
这篇关于c#使用reflection从派生类中获取私有成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!