【问题标题】:How to update a property using Type.GetProperties() method?如何使用 Type.GetProperties() 方法更新属性?
【发布时间】:2010-04-08 10:14:30
【问题描述】:

我有一个类属性的集合,并希望通过索引遍历集合来更新每个属性的值。

1) 我以这种方式创建属性集合

private PropertyInfo[] GetPropertiesOfMyClass()
    {
        Type myType = (typeof(myClass));
        PropertyInfo[] PropertyInfoArray = myType.GetProperties(
                                                BindingFlags.Public |
                                                BindingFlags.Instance);
        return PropertyInfoArray;                 
    }

2)现在,我想通过这种方式根据索引设置每个值的值

    public void UpdateProperty(MyClass instanceOfMyClass, string valueToUpdate, int index)
    {
      //TODO:
      //1. Get an individual property from the GetPropertyOfMyClass() using index
      //2. Update the value of an individual property of the instanceOfMyClass
    }

我希望能够像这样从控制器调用 UpdateProperty

UpdateProperty(instanceOfMyClass, valueToUpdate, indexOfTheProperty);

老实说,我不知道如何让 instanceOfMyClass 参与游戏,因为 GetProperty 只与 myClass 一起玩。

因为我看到我可以使用 Name、PropertyType、... 来获取有关属性的信息。所以,我也尝试过 GetPropertyOfMyClass()[index].SetValue(...),但我迷失在它的构造函数的参数中,所以我放弃了。

我想要的是能够仅通过使用索引来更新我的集合中属性的值。

感谢您的帮助

【问题讨论】:

  • 请记住,反射是相当昂贵的。您可能希望缓存结果,而不是一次又一次地调用GetPropertyOfMyClass()

标签: c#-3.0


【解决方案1】:

你的猜测是正确的。您使用 SetValue() 更新值 - 这是如何做到的:

GetPropertyOfMyClass()[index].SetValue( instanceOfMyClass, valueToUpdate, null);

最后一个参数can be null

索引属性的可选索引值。对于非索引属性,此值应为 null。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 2011-12-23
    • 1970-01-01
    相关资源
    最近更新 更多