简体   繁体   English

无法从Dictionary`2分配IDictionary`2

[英]IDictionary`2 not assignable from Dictionary`2

I want to determine wether a given Type object refers to a generic dictionary. 我想确定给定的Type对象是否引用了通用字典。 To achieve this I tried the solution from this answer . 为了达到这个目的,我尝试了这个答案的解决方案。 But to my surprise, the following test code prints not a generic dictionary! 但是令我惊讶的是,以下测试代码not a generic dictionary!打印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!");
}

How can it be that IDictionary`2 is not assignable from Dictionary`2 or do I something fundamentally wrong? 无法从Dictionary`2分配IDictionary`2还是我有根本上的错误?

In case it matters, I'm doing this in Visual Studio 2015 with .NET 4.6 as target. 如果有问题,我将在Visual Studio 2015中以.NET 4.6作为目标。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM