![](/img/trans.png)
[英]How to iterate over items of a list when I only have access to the object of that list and dont know the type parameter?
[英]Given a PropertyInfo object from System relfection that I know to be a list, how can I access the list and manipulate the items within the list?
所以我對反射相當陌生,但最近發現它非常有用。 但我遇到了障礙。 基本上現在我正在循環我通過反射獲得的類的屬性,並根據屬性包含的數據類型(int、string、enum 等)做一些事情,並在這樣做時修改屬性中的數據. 使用 propertyInfo.SetValue() 方法非常簡單,該方法適用於我需要處理的所有其他情況。 但是,對於列表,我不能只設置值,因為我不想設置列表的值,我希望能夠從列表中添加和刪除項目以及更改列表中項目的值。 而這一切都是動態的。 下面是我正在嘗試做的一個例子:
MyAbstractClass classInstance; //this may contain one of many classes inheriting from 'MyAbstractClass'
PropertyInfo[] properties = classInstance.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
//this would be proceeded by other type case checks, this is the case that it's a list
else if (prop.PropertyType.GetInterface(typeof(List<>).FullName) != null)
{
Type contentType = prop.PropertyType.GetGenericArguments()[0]; //get the type of data held in list
//BEGIN EXAMPLES OF WHAT I'D LIKE TO DO
prop.GetValue(classInstance).Add(Activator.CreateInstance(contentType));
prop.GetValue(classInstance).RemoveAt(3);
prop.GetValue(classInstance)[1] = someDataThatIKnowIsCorrectType;
}
}
僅僅通過互聯網研究,我已經想通了很多其他東西,也學到了很多東西,但是我一直無法找到我試圖拼湊的最后一塊拼圖,或者如果我找到了,可能無法識別我的問題的解決方案看到遇到它。
謝謝您的幫助!
您可以將值轉換為IList
並使用Add(object value)
方法:
class MyClass
{
public List<int> MyProperty { get; set; }
}
var x = new MyClass {MyProperty = new List<int>()};
var list = (IList)x.GetType().GetProperty(nameof(MyClass.MyProperty)).GetValue(x);
list.Add(1);
list.Add(2);
list.RemoveAt(0);
list[0] = 3;
Console.WriteLine(list[0]); // prints 3
我個人也會像這樣實現屬性類型檢查:
var isIList = prop.PropertyType.GetInterfaces().Any(i => i.IsConstructedGenericType && i.GetGenericTypeDefinition() == typeof(IList<>))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.