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

标签 c# generics dictionary

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

我该怎么做?

最佳答案

假设您不能在 Values 集合的类型中使您的方法通用,您可以使用动态:

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

关于c# - 将对象转换为 Dictionary<TKey, TValue>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13654258/

相关文章:

java - java泛型的区别

C++ 映射迭代和堆栈损坏

Python字典的Javascript实现

C# 使用递归打印一个数的幂

c# - 如何从 C# 服务终止 Java 应用程序

java - 执行时确定实例字段类型的通用参数

c# - 使用 ToDictionary 构建排序字典

c# - 尝试用另一种语言解密时 AES 解密错误

c# - 正则表达式去除 JavaScript 双斜杠 (//) 风格的注释

c# - 在反序列化期间委托(delegate)调用泛型类内部的泛型方法挂住 CPU