代码之家  ›  专栏  ›  技术社区  ›  TK.

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

  •  3
  • TK.  · 技术社区  · 15 年前

    我有以下结构:

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

    是否可以使用父类中的反射来访问子类中的commandCollection?如果没有任何建议,我如何才能做到这一点?

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

    编辑2: 所有的评论都说。。。只需在子类中添加一个function的属性,我就不能像它那样由VS设计器自动生成。我真的不想每次在设计师身上换东西的时候都要重新做我的工作!

    2 回复  |  直到 15 年前
        1
  •  9
  •   Ani    15 年前
    // _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);
    

    数组协方差应确保转换成功。

        2
  •  1
  •   Dan Bryant    15 年前

    这是可能的,尽管这是一个非常糟糕的主意。

        var field = GetType().GetField("_commandCollection", BindingFlags.Instance | BindingFlags.NonPublic);
    

    protected abstract IEnumerable<IDBCommand> GetCommands();