change variable using reflection

C

Conny Hell

Hi!

I would like to access and change the value of a
variable through reflection. IMHO this is the way
I can do it having the variables-name in a string.

If the decleration is done class-wide I can do what
I want.
-------------------------
public class Test {
private string ChangeThis = "ABC";
...
//access and change
FieldInfo fx2 =
this.GetType().GetField("ChangeThis",BindingFlags.NonPublic |
BindingFlags.Instance);
fx2.SetValue(this, "CBA");
}
------------------------
But how to perform this if the variable is set and declared in
a function?

public class Test {
public void DoThis{
ChangeThis = "XYZ";
....
//now try to change the variable
???????????
}
}
I tried the:
MemberInfo[] mi =
this.GetType().GetMember("DoThis",MemberTypes.Method,BindingFlags.NonPublic
| BindingFlags.Instance);
FieldInfo fx4 =
mi[0].GetType().GetField("ChangeThis",BindingFlags.NonPublic|
BindingFlags.Static|BindingFlags.Instance);

...and much more things with the same result: No success!

thank you
Conny
 
M

Mattias Sjögren

Conny,

You can't reflect on local variables that way. They are not fields so
there's no corresponding FieldInfo object to retrieve.



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top