我需要將一組子項從一個列表複製到另一個列表。但是我不知道列表中有哪些項目 - 或者即使傳遞的對象是列表。如何使用泛型和反射覆制列表子集
我可以看到,如果對象是由下面的代碼
t = DataSource.GetType();
if (t.IsGenericType)
{
Type elementType = t.GetGenericArguments()[0];
}
我看不到的是如何才能到列表中的各個對象,所以我可以在需要的對象複製到一個新的列表清單。
我需要將一組子項從一個列表複製到另一個列表。但是我不知道列表中有哪些項目 - 或者即使傳遞的對象是列表。如何使用泛型和反射覆制列表子集
我可以看到,如果對象是由下面的代碼
t = DataSource.GetType();
if (t.IsGenericType)
{
Type elementType = t.GetGenericArguments()[0];
}
我看不到的是如何才能到列表中的各個對象,所以我可以在需要的對象複製到一個新的列表清單。
你寫的代碼不會告訴你,如果類型是一個列表。
你可以做的是:
IList list = DataSource as IList;
if (list != null)
{
//your code here....
}
這會告訴你,如果數據源實現了IList
接口。
另一種方式將是:
t = DataSource.GetType();
if (t.IsGenericType)
{
Type elementType = t.GetGenericArguments()[0];
if (t.ToString() == string.Format("System.Collections.Generic.List`1[{0}]", elementType))
{
//your code here
}
}
((IList) DataSource)[i]
將獲得從列表中i
個元素,如果它實際上是一個列表。
大多數列表類型實行非通用System.Collections.IList
:
IList sourceList = myDataSource as IList;
if (sourceList != null)
{
myTargetList.Add((TargetType)sourceList[0]);
}
您也可以using System.Linq;
並執行以下操作:
IEnumerable sourceList = myDataSource as IEnumerable;
if (sourceList != null)
{
IEnumerable<TargetType> castList = sourceList.Cast<TargetType>();
// or if it can't be cast so easily:
IEnumerable<TargetType> convertedList =
sourceList.Cast<object>().Select(obj => someConvertFunc(obj));
myTargetList.Add(castList.GetSomeStuff(...));
}
我認爲 - 應該是= – recursive 2010-10-23 15:30:17
它應該 - 謝謝:) – 2010-10-23 15:33:32
Yikes!字符串比較有什麼用?正確的方法是't.GetGenericTypeDefinition()== typeof(List <>)' – 2010-10-23 16:00:48