开发者

Getting variable by name in C#

开发者 https://www.devze.com 2023-02-12 06:36 出处:网络
Is there a way开发者_运维问答 to get the value of a variable just by knowing the name of it, like this:

Is there a way开发者_运维问答 to get the value of a variable just by knowing the name of it, like this:

double temp = (double)MyClass.GetValue("VariableName");

When I normally would access the variable like this

double temp = MyClass.VariableName;


You could use reflection. For example if PropertyName is a public property on MyClass and you have an instance of this class you could:

MyClass myClassInstance = ...
double temp = (double)typeof(MyClass).GetProperty("PropertyName").GetValue(myClassInstance, null);

If it's a public field:

MyClass myClassInstance = ...
double temp = (double)typeof(MyClass).GetField("FieldName").GetValue(myClassInstance);

Of course you should be aware that reflection doesn't come free of cost. There could be a performance penalty compared to direct property/field access.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号