【发布时间】: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