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
159 views
in Technique[技术] by (71.8m points)

c# - Get and set the field value by passing 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 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

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

1 Reply

0 votes
by (71.8m points)

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.


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

...