相关疑难解决方法(0)

确定类型是否为字典

如何判断Type是否为 Dictionary<,>

目前唯一对我有用的是我真的知道这些论点.

例如:

var dict = new Dictionary<string, object>();
var isDict = dict.GetType() == typeof(Dictionary<string, object>; // This Works
var isDict = dict.GetType() == typeof(Dictionary<,>; // This does not work
Run Code Online (Sandbox Code Playgroud)

但字典并不总是<string, object>如此,如何在不知道参数的情况下检查它是否是字典而不必检查名称(因为我们还有其他包含该字的类Dictionary.

c# generics dictionary

40
推荐指数
3
解决办法
2万
查看次数

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

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

我该怎么做呢?

c# generics dictionary

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×2

dictionary ×2

generics ×2