IDictionary`2不能从IDictionary转发?

g.t*_*w.d 1 c# dictionary

我有一个ViewModel类型的属性IDictionary<string, string>.我将浏览该属性列表ViewModel并使用反射来确定它是否是字典.

目前我有:

if (typeof(IDictionary).IsAssignableFrom(propDescriptor.PropertyType))
Run Code Online (Sandbox Code Playgroud)

然而,这始终是假的,因为propDescriptor.PropertyTypeIDictionary`2.任何想法我怎么能让它工作?另外,为什么这不起作用?


我只是将我的属性更改为IDictionary而不是IDictionary.

编辑:不知道我的泛型去了哪里,但上面句子中的第二个IDictionary有字符串,字符串.

Jep*_*sen 5

它不起作用的原因是通用IDictionary<,>接口没有非泛型IDictionary作为基接口.

也许这就是你想要的:

var type = propDescriptor.PropertyType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>))
{ // ...
Run Code Online (Sandbox Code Playgroud)

编辑:如果上面的代码将只检查type宣布IDictionary<X, Y>一些XY.如果你也想处理情况的情况下type代表的类或结构器具 IDictionary<X, Y>(甚至是源自一个接口IDictionary<X, Y>),那么试试这个:

Func<Type, bool> isGenericIDict =
  t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IDictionary<,>);
var type = propDescriptor.PropertyType;
if (isGenericIDict(type) || type.GetInterfaces().Any(isGenericIDict))
{ // ..
Run Code Online (Sandbox Code Playgroud)