2013-10-28 42 views
2

我有一個List<object>,我想轉換爲強類型數組。問題是我在編譯時不知道列表類型,因爲它可能是許多對象之一。如何動態調用Cast <T>

本質上,如果我有Type objectType = list[0].GetType()我希望能夠撥打list.Cast<objectType>().ToArray()

我該怎麼做?我嘗試使用Reflection如下:

Type listType = list[0].GetType(); 
MethodInfo castMethod = typeof(Enumerable).GetMethod("Cast", BindingFlags.Static | BindingFlags.Public); 
castMethod = castMethod.MakeGenericMethod(new Type[] { listType }); 
castMethod.Invoke(null, new object[] { list}); 

該調用返回一個看起來沒有公共方法的CastIterator。

+1

你打算如何使用**結果? –

+0

@ReedCopsey這樣做的根本原因是系統將東西放入對象緩存中。之所以提前不知道類型,是因爲它是一種常見的緩存方法,淺層克隆一個域對象以刪除它所保存的任何引用以避免引用泄漏(即數據庫連接,文件等)。 – Sam

回答

4

你可以使用:

MethodInfo castMethod = typeof(Enumerable).GetMethod("Cast", BindingFlags.Static | BindingFlags.Public); 
castMethod = castMethod.MakeGenericMethod(new Type[] { listType }); 
object castIterator = castMethod.Invoke(null, new object[] { list}); 
var toArrayMethod = typeof(Enumerable).GetMethod("ToArray", BindingFlags.Static | BindingFlags.Public); 
toArrayMethod = toArrayMethod.MakeGenericMethod(new Type[] { listType }); 
object theArray = toArrayMethod.Invoke(null, new[] {castIterator}); 

在本月底,theArray將是已強類型的數組。

+0

謝謝!作品一種享受。 – Sam