【发布时间】: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