可能重复:
我可以使用Reflection设置属性值吗?
当我只有属性的字符串名称时,如何使用反射设置类的静态属性?比如我有:
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;
}
Run Code Online (Sandbox Code Playgroud)
我不知道应该如何使用属性名称字符串设置属性的值.一切都充满活力.我可以使用列表中的5个项目设置5个静态属性,每个项目都有不同的类型.
谢谢你的帮助.
回答:
Type _type = Type.GetType("Namespace.AnotherNamespace.ClassName");
PropertyInfo _propertyInfo = _type.GetProperty("Field1");
_propertyInfo.SetValue(_type, _newValue, null);
Run Code Online (Sandbox Code Playgroud)
Sof*_*ide 25
你可以尝试这样的事情
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);
}
Run Code Online (Sandbox Code Playgroud)
Bea*_*692 14
您可以像这样获取PropertyInfo并设置值
var propertyInfo=obj.GetType().GetProperty(propertyName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
propertyInfo.SetValue(obj, value,null);
Run Code Online (Sandbox Code Playgroud)