2010-09-29 111 views
0

比方說,我已經使用反射檢索了一個System.Type對象,並且希望使用該類型將List<Object>轉換爲另一個該類型的List。使用System.Type對象轉換列表<Object>

如果我嘗試:

Type type = GetTypeUsingReflection(); 
var myNewList = listObject.ConvertAll(x => Convert.ChangeType(x, type)); 

我得到一個異常,因爲對象沒有實現IConvertible接口。有沒有辦法解決這個問題或其他方式來解決這個問題?

+0

舊類型和新類型之間的關係是什麼?一個如何轉換到另一個? – LukeH 2010-09-29 16:25:29

回答

0
Type type = typeof(int); // could as well be obtained by Reflection 

var objList = new List<object> { 1, 2, 3 }; 
var intList = (IList) Activator.CreateInstance(
    typeof(List<>).MakeGenericType(type) 
    ); 

foreach (var item in objList) 
    intList.Add(item); 

// System.Collections.Generic.List`1[[System.Int32, ...]] 
Console.WriteLine(intList.GetType().FullName); 

但是爲什麼你會在地球上需要它?

+0

謝謝,像魅力一樣工作!那麼原因是這樣的:讓我們說,爲了依賴注入的目的,我通過反射可以找到類實現一個特定的接口與一個方法,採取List 作爲參數。在運行時,我不知道T是什麼,但我可以檢索類型。不是最好的解釋,但希望有提示。 – 2010-09-29 20:17:05

+0

你看,我問的原因是我最近在一個操作NHibenate對象和同步不同數據庫的層上工作 - 而且,當它變得越來越複雜,我們需要保持抽象的東西時,我開始介紹越來越像這樣的代碼示例反映了瘋狂。然後,我剛剛刪除了泛型和類型安全(無論如何,因爲這些值只是通過反射來獲得和設置的),並且使所有的類型都變成無類型和簡單的結果,這是後來難以估計的最好解決方案。儘可能保持簡單。 – 2010-09-29 20:27:45

4

你提出的方案實際上不會反正工作 - 它只會創建另一個List<Object>,因爲ChangeType返回類型爲Object

假設你只是想鑄造,你可以做這樣的事情:

using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.Reflection; 

class Test 
{ 
    private static List<T> ConvertListImpl<T>(List<object> list) 
    { 
     return list.ConvertAll(x => (T) x); 
    } 

    // Replace "Test" with the name of the type containing this method 
    private static MethodInfo methodDefinition = typeof(Test).GetMethod 
     ("ConvertListImpl", BindingFlags.Static | BindingFlags.NonPublic); 

    public static IEnumerable ConvertList(List<object> list, Type type) 
    { 
     MethodInfo method = methodDefinition.MakeGenericMethod(type); 
     return (IEnumerable) method.Invoke(null, new object[] { list }); 
    } 

    static void Main() 
    { 
     List<object> objects = new List<object> { "Hello", "there" }; 
     List<string> strings = (List<string>) ConvertList(objects, 
                  typeof(string)); 

     foreach (string x in strings) 
     { 
      Console.WriteLine(x); 
     } 
    } 
} 
0

鑄造是很少使用時類型不是在設計時知道的。一旦你將新的對象列表轉換爲新類型,你將如何使用新類型?你不能調用一個方法,該類型公開(不使用更多的思考)

0

有沒有辦法爲類型系統從類型變量的存儲類型T到T類型的泛型參數

技術上您可以創建正確類型的通用列表(使用反射),但類型信息在編譯時不可用。