在 C# 中按名称获取变量 [英] Getting variable by name in C#

查看:71
本文介绍了在 C# 中按名称获取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以通过知道变量的名称来获取它的值,就像这样:

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;

推荐答案

您可以使用 反射.例如,如果 PropertyName 是公共 属性MyClass 上,你有一个这个类的实例,你可以:

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);

如果是公共字段:

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.

这篇关于在 C# 中按名称获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆