2012-11-30 2 views
2

나는 일반적인 사전의에서 작동 C#에서 기능을 가지고 :캐스트 개체

public static string DoStuff<TKey, TValue>(Dictionary<TKey, TValue> dictionary) 
{ 
    // ... stuff happens here 
} 

나는 또한 객체를 통해 루프 기능을 가지고있다. 이러한 객체 중 하나가 Dictionary <> 일 경우 해당 일반 함수로 전달해야합니다. 그러나 키 또는 값의 유형이 컴파일 타임에 무엇인지 알 수 없습니다.

foreach (object o in Values) 
{ 
    if (/*o is Dictionary<??,??>*/) 
    { 
     var dictionary = /* cast o to some sort of Dictionary<> */; 
     DoStuff(dictionary); 
    } 
} 

어떻게해야합니까? 당신이 Value 모음의 모든 사전이 동일한 지 알고 있다면

+3

가 대신 IDictionary를 사용할 수 있습니다

foreach (object o in values) { Type t = o.GetType(); if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>)) { string str = DoStuff((dynamic)o); Console.WriteLine(str); } } 

이 또는 당신이 반사를 사용할 수 있습니다 ? –

+0

http://stackoverflow.com/questions/123181/testing-if-an-object-is-a-dictionary-in-c-sharp 가능한 중복 – itsme86

+0

사용하려면 DoStuff 함수를 다시 작성해야하지 않습니까? IDictionary 유형? 그것은 실제로 선택 사항이 아닙니다. – Ryan

답변

4

, 당신은 동적 사용할 수 있습니다

foreach (object o in values) 
{ 
    Type t = o.GetType(); 
    if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>)) 
    { 
     var typeParams = t.GetGenericArguments(); 
     var method = typeof(ContainingType).GetMethod("DoStuff").MakeGenericMethod(typeParams); 
     string str = (string)method.Invoke(null, new[] { o }); 
    } 
} 
+0

+1. 실제로 리플렉션 코드는 내가 생각한 것만 큼 나쁘지 않습니다. –

3

도 함수가 일반적인 확인 :

void DealWithIt<T,V>(IEnumerable Values) 
{ 
foreach (object item in Values) 
{ 
    var dictionary = item as Dictionary<T,V>; 
    if (dictionary != null) 
    { 
     DoStuff<T,V>(dictionary); 
    } 
} 

그렇지 않으면 제네릭이 아닌 IDictionary 심각한 반사 코드로 다이빙을하기 전에 DoStuff 전달 될 사용하는 것이 좋습니다. 당신이 Values 수집의 종류에 일반적인 당신의 방법을 만들 수없는 가정