获取变量的名字在C# [英] Getting variable by name in C#
本文介绍了获取变量的名字在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法只是知道它的名字,像这样得到一个变量的值:
双TEMP =(双)MyClass.GetValue(变量名);
当我通常会访问变量像这样
双TEMP = MyClass.VariableName;
解决方案
您可以使用反射。例如,如果属性名
是一个公共财产在 MyClass的
,你有这个类的一个实例,你可以:
MyClass的myClassInstance = ...
双TEMP =(双)typeof运算(MyClass的).GetProperty(属性名)的GetValue(myClassInstance,NULL);
如果它是一个公共场:
MyClass的myClassInstance = ...
双TEMP =(双)typeof运算(MyClass的).GetField(字段名)的GetValue(myClassInstance)。
当然,你应该知道,反射不来免费的。相比于直接财产/字段访问可能会有性能上的损失。
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.
这篇关于获取变量的名字在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文