代码之家  ›  专栏  ›  技术社区  ›  Bill Tür stands with Ukraine Ajay Pawar

IDictionary“2”不可从Dictionary“2”分配

  •  0
  • Bill Tür stands with Ukraine Ajay Pawar  · 技术社区  · 7 年前

    我想确定是否 Type 对象引用泛型词典。为了实现这一点,我尝试了以下解决方案 this answer .但令我惊讶的是,下面的测试代码 not a generic dictionary!

    private void Test()
    {
        var dict = new Dictionary<string, string>();
        var type = dict.GetType();
        
        if (type.IsGenericType &&
                typeof(IDictionary<,>).IsAssignableFrom(type.GetGenericTypeDefinition()))
            Console.WriteLine("a generic dictionary");
        else
            Console.WriteLine("not a generic dictionary!");
    }
    

    怎么会这样 IDictionary`2 不可从中分配 Dictionary`2 还是我有什么根本错误?

    如果有必要,我将在Visual Studio 2015中使用。NET 4.6作为目标。

    1 回复  |  直到 4 年前
        1
  •  1
  •   Lee    7 年前

    您需要搜索类型的接口,并检查是否有 IDictionary<K, V> 接口:

    bool isDict = type.GetInterfaces().Any(it => it.IsGenericType && it.GetGenericTypeDefinition() == typeof(IDictionary<,>));