Get and set the field value by passing the name

I have a field in a class with a random name like:

class Foo { public string a2de = "e2" } 

I have the name of this field in another variable, for example:

 string vari = "a2de" 

Can I get or set the value of a2de field using vari value?

as:

 getvar(vari) 

or

 setvar(vari) = "e3" 
+4
source share
3 answers

You must use reflection.

To get the property value on targetObject :

 var value = targetObject.GetType().GetProperty(vari).GetValue(targetObject, null); 

To get the value of a field, it looks like:

 var value = targetObject.GetType().GetField(vari).GetValue(targetObject, null); 

If the property / field is not public or inherited from the base class, you need to specify explicit BindingFlags in GetProperty or GetField .

+9
source

You can do this with reflection (e.g. Type.GetField , etc.), but this should usually be the last thing.

Do you consider using Dictionary<string, string> and using the "variable name" instead?

+5
source

You will need to use Reflection to access the variable by name. Like this:

 class Foo { int namedField = 1; string vari = "namedField" void AccessField() { int val = (int) GetType().InvokeMember(vari, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField, null, this, null); // now you should have 1 in val. } } 
+1
source

Source: https://habr.com/ru/post/1342621/


All Articles