Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 like:

string vari = "a2de"

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

like:

getvar(vari)

or

setvar(vari) = "e3"
See Question&Answers more detail:os

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

1 Answer

You have to use reflection.

To get the value of a property on targetObject:

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

To get the value of a field it's similar:

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

If the property/field is not public or it has been inherited from a base class, you will need to provide explicit BindingFlags to GetProperty or GetField.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...