将对象转换为Dictionary <tkey,tvalue =“”> </tkey,>

时间:2012-11-30 22:43:53

标签: c# generics dictionary

我在C#中有一个函数,它在泛型Dictionary上运行:

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

我还有一个循环对象的函数。如果其中一个对象是Dictionary&lt;&gt;,我需要将它传递给该泛型函数。但是,我不知道在编译时键或值的类型是什么:

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

我该怎么做?

2 个答案:

答案 0 :(得分:5)

假设您无法在Values集合的类型中使您的方法具有通用性,您可以使用dynamic:

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

或者你可以使用反射:

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 });
    }
}

答案 1 :(得分:3)

如果你知道Value集合中的所有词典都是相同的,那么你的函数也是通用的:

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

相关问题