2012-10-19 52 views
21

可能重复:
.Net - Reflection set object property
Setting a property by reflection with a string valueC#动态设置属性

我敢肯定有这样做的一个简单的方法,我是厚,但我可以”琢磨出我的生活。

我有一个对象具有多个属性。我们调用对象objName。我试图创建一个方法,只是用新的属性值更新对象。

我希望能够做的方法如下:

private void SetObjectProperty(string propertyName, string value, ref object objName) 
{ 
    //some processing on the rest of the code to make sure we actually want to set this value. 
    objName.propertyName = value 
} 

最后,调用:

SetObjectProperty("nameOfProperty", textBoxValue.Text, ref objName); 

希望的问题是充实就够了。让我知道你是否需要更多细节。

感谢您的回答!

+0

@DavidArcher在C#中没有'rel'键盘...我认为你的意思是'ref'?除非您打算更改实际的实例,否则不需要将对象作为'ref'传递。 – James

+0

的确,我确实是指ref,是的,我打算改变实际的实例。 –

回答

40

objName.GetType().GetProperty("nameOfProperty").SetValue(objName, objValue, null)

+1

你应该在'GetProperty()'内使用'propertyName'。 – Anonymous

+0

如果“* nameOfProperty *”不存在? – James

+0

例外当然,你可以使用GetProperties来测试。 – josejuan

26

您可以使用Reflection来执行此操作,例如

private void SetObjectProperty(string propertyName, string value, object obj) 
{ 
    PropertyInfo propertyInfo = obj.GetType().GetProperty(propertyName); 
    // make sure object has the property we are after 
    if (propertyInfo != null) 
    { 
     propertyInfo.SetValue(obj, value, null); 
    } 
} 
+2

支持在调用之前检查null。 –

1

首先取得属性信息,然后设置该属性的值:

PropertyInfo propertyInfo = objName.GetType().GetProperty(propertyName); 
propertyInfo.SetValue(propertyInfo, value, null); 
3

您可以使用Type.InvokeMember做到这一点。

private void SetObjectProperty(string propertyName, string value, rel objName) 
{ 
    objName.GetType().InvokeMember(propertyName, 
     BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, 
     Type.DefaultBinder, objName, value); 
} 
1

您可以通过反射做到这一点:

void SetObjectProperty(object theObject, string propertyName, object value) 
{ 
    Type type=theObject.GetType(); 
    var property=type.GetProperty(propertyName); 
    var setter=property.SetMethod(); 
    setter.Invoke(theObject, new ojbject[]{value}); 
} 

注意:错误处理故意留出的可读性的原因。