将对象转换为Dictionary <TKey,TValue>

Rya*_*yan 5 c# generics dictionary

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

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

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

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

我该怎么做呢?

Lee*_*Lee 6

假设您无法在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);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用反射:

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 });
    }
}
Run Code Online (Sandbox Code Playgroud)