48

可能重复:
.Net - 反射设置对象
属性通过反射使用字符串值设置属性

我有一个具有多个属性的对象。我们称对象为 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);

希望这个问题足够充实。如果您需要更多详细信息,请告诉我。

感谢大家的回答!

4

5 回答 5

79

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

于 2012-10-19T08:41:15.307 回答
44

您可以使用反射来做到这一点,例如

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);
    }
}
于 2012-10-19T08:38:08.253 回答
4

先获取属性信息,然后在属性上设置值:

PropertyInfo propertyInfo = objName.GetType().GetProperty(propertyName);
propertyInfo.SetValue(objName, value, null);
于 2012-10-19T08:41:34.993 回答
4

您可以使用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); 
} 
于 2012-10-19T08:43:12.480 回答
2

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

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});
}

注意:为了可读性,故意省略了错误处理。

于 2012-10-19T08:44:43.053 回答