1
我有一個類的屬性的集合,並希望通過該指數遍歷集合更新每個人的價值。如何更新使用Type.GetProperties()方法的屬性?
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。
因爲我看到了,我可以使用名稱,屬性類型,...得到的屬性信息。所以,我也試着GetPropertyOfMyClass()[指數] .SetValue(...),但我失去了它的構造函數的參數,所以我放棄了。
我想要的是能夠僅僅通過使用索引來更新我的收藏屬性的值。
感謝您的幫助
請記住,這反映是相當昂貴的。不要一次又一次調用'GetPropertyOfMyClass()',你可能想要緩存結果。 – tanascius 2010-04-08 10:23:34