Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

c# use reflection to get a private member variable from a derived class

I have the following structure:

abstract class Parent {}


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

    // Auto-generated code here
}

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?

EDIT: 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: 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
// _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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...