使用字符串访问属性 [英] Access to Attributes using a String
问题描述
由于与对象字段的名称相同,我怎么能得到的参考对象字段的字符串?
例如,说我传递一个字符串所谓FIELD1到GetFieldByStr方法,对象有一个字段名字段1,我怎么能到FIELD1对象的引用?我使用反射莫名其妙假设
类示例{
私人FieldExample ATTR1;
无效GetFieldByStr(字符串str){
//我们得到的字段1字符串来传递,现在我想
//得到FIELD1属性。
}
}
< A HREF =http://msdn.microsoft.com/en-us/library/f7ykdhsy.aspx相对=nofollow>您需要使用反射:
字段信息字段= typeof运算(例).GetField(STR);
对象值= field.GetValue(本);
(对于属性,使用的PropertyInfo
)
注意值
是一个对象;为了做任何有用的事情,你需要将其转换为一些类或接口(或使用动态
在C#4)。
Given a string with the same name of an object field, how can I get the reference to the object field?
For example, say I pass in a string called "field1" to the GetFieldByStr method, and the object has an field name field1, how can I get a reference to the field1 object? I'm assuming using reflection somehow.
class Example {
private FieldExample attr1;
void GetFieldByStr(String str) {
// We get passed in "field1" as a string, now I want
// to get the field1 attribute.
}
}
FieldInfo field = typeof(Example).GetField(str);
object value = field.GetValue(this);
(For properties, use PropertyInfo
)
Note that value
is an object; in order to do anything useful with it, you'll need to cast it to some class or interface (or use dynamic
in C# 4).
这篇关于使用字符串访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!