簡體   English   中英

c#在運行時動態創建通用列表

[英]c# Create generic list dynamically at runtime

下面就例如這個帖子 ,我發現了如何動態地創建通用類型的列表。 現在,我的問題是我想將項目從未知來源列表添加到創建的列表中,有什么方法可以實現?

編輯我從包含業務對象的源列表開始,但是由於需要下游綁定,因此我絕對需要正確的輸出列表類型。

我的非編譯代碼如下:

IList<object> sourceList; // some list containing custom objects
Type t = typeof(IList).MakeGenericType(sourceList[0].GetType());
IList res = (IList)Activator.CreateInstance(t);
foreach (var item in sourceList) {
    reportDS.Add(item); // obviously does not compile
}

有一些原因導致此代碼無法正常工作。

首先,您需要創建一個具體類型的實例。 您正在使用一個非泛型接口( IList ),並試圖從中創建一個泛型類型。 您需要typeof(List<>)

其次,您要調用AddItem ,它不是IList上的方法。 您需要調用Add ,這就是為什么代碼無法編譯的原因。

此代碼將執行您想要的操作:

IList<object> sourceList; // some list containing custom objects
Type t = typeof(List<>).MakeGenericType(sourceList[0].GetType());
IList res = (IList)Activator.CreateInstance(t);

foreach(var item in sourceList)
{
    res.Add(item);
}

但是, sourceList[0]擁有正確類型的假設可能會讓您大吃一驚。 如果該列表包含與列表中第一項類型不兼容的一系列對象,則添加到res任何嘗試都會失敗。 正如評論中提到的,最好創建一個List<object>來保存項目。

我建議將您的代碼移到通用類或函數中,將反射移到更高的層次:

private static List<T> CloneListAs<T>(IList<object> source)
{
    // Here we can do anything we want with T
    // T == source[0].GetType()
    return source.Cast<T>().ToList();
}

調用它:

IList<object> sourceList; // some list containing custom objects
// sourceList = ...

MethodInfo method = typeof(this).GetMethod("CloneListAs");
MethodInfo genericMethod = method.MakeGenericMethod(sourceList[0].GetType());

var reportDS = genericMethod.Invoke(null, new[] {sourceList});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM