2014-07-09 4 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