get an object by its variable name

  • Thread starter Thread starter Eric Chappuis
  • Start date Start date
E

Eric Chappuis

How can I use reflexion to get an object by its local name.

I found the Type.GetMember(string name) which return a MemberInfo, but I
can't jump from MemberInfo to the member itself.

I would like to fill the function getByName :
class A {
B b1 = new B();
B b2 = new B();
public getByName (string s) {
// how to retrieve object b1 if (s == "b1") or b2 if (s == "b2")
// or to retrive an object by its name
}
}

class B { //... }
 
I found the Type.GetMember(string name) which return a MemberInfo, but I
can't jump from MemberInfo to the member itself.

you cannot get the instances of objects with reflection. reflection only
deals with decription of classes and not with instances of these classes.

got it? the same way looking at the specs you can say how long is the new
model of Porshe but you cannot ask about the colour of any particular copy.

Regards, Wiktor
 
Can we see teh problem from the point of view "Find a member of A and not
Find an instance of B"

class A {
B b1 = new B();
B b2 = new B();
public getByName (string s) {
if ( s == "b1" )
return b1;
else
return b2;
}
}

how about that? I am not sure what you are trying to do.
 
you cannot get the instances of objects with reflection. reflection only
deals with decription of classes and not with instances of these classes.

got it? the same way looking at the specs you can say how long is the new
model of Porshe but you cannot ask about the colour of any particular copy.

Wiktor: Sorry, but you're wrong. Reflection does work with general
info about classes, but you can also use it to work with instances --
read and write to properties, call methods, etc. That's how the
PropertyGrid and DataGrid work.

Eric: MemberInfo is a base class; it applies to fields, properties,
methods, etc. Getting and setting don't apply to methods, so those
aren't introduced in the MemberInfo class; they're introduced in
descendant classes. In this case, you're dealing with a field, so you
want to cast the MemberInfo to a FieldInfo, and then call GetValue,
passing in the object instance whose field you want to read.

Something like this (untested code):

class A {
B b1 = new B();
B b2 = new B();
public object getByName (string s) {
MemberInfo memberInfo = GetType().GetMember(s);
return ((FieldInfo) memberInfo).GetValue(this);
}
}
 
Not exactly indeed...

I try to get the generic. one I will maybe fill a static hashtable in B when
building it and calling

B b1 = new B("b1");

So I can use the hashtable in my function
 
Wiktor: Sorry, but you're wrong. Reflection does work with general
info about classes, but you can also use it to work with instances --
read and write to properties, call methods, etc. That's how the
PropertyGrid and DataGrid work.

thanks for correcting me.
 
Back
Top