【问题标题】:Detect if it's a Dictionary and the key is assignable from a specific type检测它是否是字典并且键可以从特定类型分配
【发布时间】:2017-08-03 06:13:49
【问题描述】:

我正在处理自定义JsonConverter,并覆盖CanConvert-方法。

public override bool CanConvert(Type objectType)
{
    return (typeof(IDictionary).IsAssignableFrom(objectType) ||
            TypeImplementsGenericInterface(objectType, typeof(IDictionary<,>)));
}

private static bool TypeImplementsGenericInterface(Type concreteType, Type interfaceType)
{
    return concreteType.GetInterfaces()
           .Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType);
}

非常受this answer 的启发。问题是,如果字典的键是特定类型,我只想返回 true。例如,如果键的类型为Bar,或者继承/实现Bar,我只想返回true。价值无所谓。该值可以是任何类型。

Dictionary<string, int> // false
Dictionary<Bar, string> // true
Dictionary<Foo, string> // false
Dictionary<Bar, Foo> // true
Dictionary<BarSubClass, Foo> // true

我如何从 Type 检测它是否是 Dictionary 并且密钥是否可以从特定类型分配?

到目前为止我已经尝试过:

typeof(IDictionary<Bar, object>).IsAssignableFrom(objectType)

不幸的是,这会返回false

【问题讨论】:

  • @derape - 不同之处在于我没有实例。我有一个类型。另外,我已经知道如何检查它是否可以从字典中分配。我还需要检查它是否有特定的键。
  • 你必须深入研究接口定义Generic Arguments
  • @smoksnes 你不需要实例来做到这一点,只需要类型

标签: c# dictionary reflection


【解决方案1】:

您必须检查泛型类型和第一个类型参数 (TKey):

concreteType.GetInterfaces().Any(i => i.IsGenericType &&
    (i.GetGenericTypeDefinition() == typeof(IDictionary<,>)) &&
    typeof(Bar).IsAssignableFrom(i.GetGenericArguments()[0]));

【讨论】:

  • 效果很好。正是我想要的。
猜你喜欢
  • 2017-05-06
  • 2014-02-03
  • 1970-01-01
  • 2017-09-02
  • 2012-12-28
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
  • 1970-01-01
相关资源
最近更新 更多