在c#中是否有一种方法,我可以使用反射来设置对象属性?
Ex:
MyObject obj = new MyObject();
obj.Name = "Value";
我要设置obj。带有反射的名称。喜欢的东西:
Reflection.SetProperty(obj, "Name") = "Value";
有什么办法可以做到吗?
在c#中是否有一种方法,我可以使用反射来设置对象属性?
Ex:
MyObject obj = new MyObject();
obj.Name = "Value";
我要设置obj。带有反射的名称。喜欢的东西:
Reflection.SetProperty(obj, "Name") = "Value";
有什么办法可以做到吗?
当前回答
是的,使用系统。反射:
using System.Reflection;
...
string prop = "name";
PropertyInfo pi = myObject.GetType().GetProperty(prop);
pi.SetValue(myObject, "Bob", null);
其他回答
或者你可以在你自己的扩展类中包装Marc的一行代码:
public static class PropertyExtension{
public static void SetPropertyValue(this object obj, string propName, object value)
{
obj.GetType().GetProperty(propName).SetValue(obj, value, null);
}
}
像这样叫它:
myObject.SetPropertyValue("myProperty", "myValue");
为了更好地衡量,让我们添加一个方法来获取属性值:
public static object GetPropertyValue(this object obj, string propName)
{
return obj.GetType().GetProperty(propName).GetValue (obj, null);
}
是的,你可以使用type . invokember ():
using System.Reflection;
MyObject obj = new MyObject();
obj.GetType().InvokeMember("Name",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
Type.DefaultBinder, obj, "Value");
如果obj没有名为Name的属性,或者它无法设置,这将抛出异常。
另一种方法是获取属性的元数据,然后对其进行设置。这将允许你检查属性是否存在,并验证它是否可以被设置:
using System.Reflection;
MyObject obj = new MyObject();
PropertyInfo prop = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if(null != prop && prop.CanWrite)
{
prop.SetValue(obj, "Value", null);
}
你还可以:
Type type = target.GetType();
PropertyInfo prop = type.GetProperty("propertyName");
prop.SetValue (target, propertyValue, null);
其中target是将设置其属性的对象。
你也可以使用类似的方式访问字段:
var obj=new MyObject();
FieldInfo fi = obj.GetType().
GetField("Name", BindingFlags.NonPublic | BindingFlags.Instance);
fi.SetValue(obj,value)
在我的例子中,我们绑定到一个私有实例级字段。
是的,使用系统。反射:
using System.Reflection;
...
string prop = "name";
PropertyInfo pi = myObject.GetType().GetProperty(prop);
pi.SetValue(myObject, "Bob", null);