C#动态设置属性

Dav*_*her 33 c# methods

可能重复:
.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
}
Run Code Online (Sandbox Code Playgroud)

最后,电话:

SetObjectProperty("nameOfProperty", textBoxValue.Text, ref objName);
Run Code Online (Sandbox Code Playgroud)

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

谢谢你的答案!

jos*_*uan 59

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

  • 你应该在`GetProperty()`中使用`propertyName`. (3认同)
  • 如果“*nameOfProperty*”不存在怎么办? (2认同)

Jam*_*mes 37

您可以使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在调用之前检查null的道具. (2认同)
  • 我通常还会检查“可以写入”:`if (propertyInfo != null && propertyInfo.CanWrite)`。 (2认同)