C#动态设置属性

时间:2012-10-19 08:36:44

标签: c# methods

  

可能重复:
  .Net - Reflection set object property
  Setting a property by reflection with a string value

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

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

感谢所有答案!

5 个答案:

答案 0 :(得分:49)

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

答案 1 :(得分:32)

您可以使用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 :(得分: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); 
} 

答案 3 :(得分:1)

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

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

答案 4 :(得分: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});
}

注意:为了便于阅读,故意遗漏错误处理。

相关问题