使用属性名称设置属性值 [英] Set property value using property name
本文介绍了使用属性名称设置属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
我可以使用Reflection设置属性值吗?
当仅具有属性的字符串名称时,如何使用反射设置类的静态属性?例如,我有:
How do I set a static property of a class using reflection when I only have its string name of the property? For instance I have:
List<KeyValuePair<string, object>> _lObjects = GetObjectsList();
foreach(KeyValuePair<string, object> _pair in _lObjects)
{
//class have this static property name stored in _pair.Key
Class1.[_pair.Key] = (cast using typeof (_pair.Value))_pair.Value;
}
我不知道如何使用属性名称字符串。一切都是动态的。我可以使用列表中的5种不同类型的项来设置类的5个静态属性。
I don't know how I should set the value of the property using the property name string. Everything is dynamic. I could be setting 5 static properties of a class using 5 items in the list that each have different types.
感谢您的帮助。
答案:
Type _type = Type.GetType("Namespace.AnotherNamespace.ClassName");
PropertyInfo _propertyInfo = _type.GetProperty("Field1");
_propertyInfo.SetValue(_type, _newValue, null);
推荐答案
您可以尝试以下类似方法
You can try something like this
List<KeyValuePair<string, object>> _lObjects = GetObjectsList();
var class1 = new Class1();
var class1Type = typeof(class1);
foreach(KeyValuePair<string, object> _pair in _lObjects)
{
//class have this static property name stored in _pair.Key
class1Type.GetProperty(_pair.Key).SetValue(class1, _pair.Value);
}
这篇关于使用属性名称设置属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文