【问题标题】:C# dynamically set property [duplicate]C#动态设置属性[重复]
【发布时间】:2012-10-09 20:06:48
【问题描述】:

可能重复:
.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);

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

感谢大家的回答!

【问题讨论】:

  • @DavidArcher C# 中没有rel 键盘...我认为您的意思是ref?除非您打算更改它的实际实例,否则无需将对象作为 ref 传递。
  • 确实,我的意思是 ref,是的,我确实打算更改实际实例。

标签: c# methods


【解决方案1】:

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

【讨论】:

  • 你应该在GetProperty()中使用propertyName
  • 如果“nameOfProperty”不存在怎么办?
  • 当然例外,你可以使用GetProperties来测试。
  • 我能够使用您的代码示例将我的 200 行代码替换为 5 行。谢谢,你拯救了我的一天。
【解决方案2】:

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

【讨论】:

  • 调用前检查 null 的道具。
  • 我通常也会检查“可以写”:if (propertyInfo != null && propertyInfo.CanWrite).
【解决方案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); 
} 

【讨论】:

    【解决方案4】:

    先获取属性信息,再设置属性值:

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

    【讨论】:

      【解决方案5】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2020-02-15
        • 2018-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-14
        • 2011-09-18
        • 2012-10-23
        相关资源
        最近更新 更多