2014-07-09 56 views
2

我嘗試編寫一個泛型類型轉換方法,該方法既適用於複雜對象又適用於對象數組。下面是我的代碼:將類型轉換對象[]轉換爲泛型類型K,這也是一個數組

public void Test() 
{ 
    MyClass2[] t2 = m.MapItem<MyClass1[], MyClass2[]>(t1); 
    return; 
} 

public K MapItem<T, K>(T source) 
{ 
    if (typeof(T).IsArray && typeof(K).IsArray) 
    { 
     Type ek = typeof(K).GetElementType(); 
     IList sourceList = (IList)source; 
     List<object> tmp = new List<object>(); 
     for (int i = 0; i < sourceList.Count; i++) 
     { 
      var k = Activator.CreateInstance(ek); 
      tmp.Add(k); 
     } 
     var resultObj = tmp.ToArray(); 
     MapItem(source, resultObj); 

     //Here i have resultObj is an object[] of the results, 
     //which is to be casted result type K 
     //BUT DOES NOT WORK!!! 
     return (K)Convert.ChangeType(resultObj, typeof(K)); 

    } 
    else 
    { 
     MethodInfo myMapperMethod = GetMyMapperMethodForThisType(typeof(T), typeof(K)); 
     return (K)myMapperMethod.Invoke(null, new object[] { source }); 
    } 
} 

public K MapItem<T, K>(T source, K dest) 
{ 
    if (typeof(T).IsArray && typeof(K).IsArray) 
    { 
     IList sourceList = (IList)source; 
     IList destList = (IList)dest; 
     for (int i = 0; i < sourceList.Count; i++) 
     { 
      MapItem(sourceList[i], destList[i]); 
     } 
     return dest; 
    } 
    else 
    { 
     MethodInfo myMapperMethod = GetMyMapperMethodForThisType(typeof(T),typeof(K)); 
     return (K) myMapperMethod.Invoke(null, new object[] { source, dest }); 
    } 
} 

private MethodInfo GetMyMapperMethodForThisType(Type type1, Type type2) 
{ 
    //some code to find appropriate function... 
} 

但是,return (K) Convert.ChangeType(y, typeof(K));不能施放從object[]K。我如何做這個鑄造從object[]返回K

注意:json序列化工作正常,但我不想使用反射或序列化。

string jsonStr = JsonConvert.SerializeObject(resultObj); 
    return JsonConvert.DeserializeObject<K>(jsonStr); 

回答

1

基本上我認爲你想避免使用List<object>。您應該創建合適大小的陣列:

IList dest = Array.CreateInstance(ek, sourceList.Count); 
for (int i = 0; i < sourceList.Count; i++) 
{ 
    dest[i] = Activator.CreateInstance(ek); 
} 
K result = (K) dest; 
// Note that this is calling MapItem<T, K>, not MapItem<T, object[]> 
MapItem(source, result); 
return result; 
+0

非常感謝:) – irfangoren