C#访问字段语法 [英] C# Accessing field syntax
本文介绍了C#访问字段语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果仅具有我要访问的变量的名称,我将如何访问对象的变量的值?在C#中.
How would I access an object's variable's value if I only have the name of the variable I wish to access? In C#.
说我有一个以数组中的字符串表示的变量名列表.例如,我将如何循环访问它们.我可以在Actionscript中执行以下操作:
Say I had a list of variable names represented as strings in an array. How would I access them in a loop, for example. I can do something like the following in Actionscript:
var arrayOfVariableNames:Array = ["name", "age", "sex"]
for each(var person:Person in persons)
{
if (person[age] > 29) //what is equivalent in c# for object[field]
{
//do something
}
}
推荐答案
您可以使用反射通过字段名称访问字段:
You can use reflection to access a field by its name :
FieldInfo ageField = typeof(Person).GetField("age");
int age = (int) field.GetValue(person);
这篇关于C#访问字段语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文