[英]IDictionary`2 is not assignable from IDictionary?
I have a property on my ViewModel
that is of type IDictionary<string, string>
. 我的
ViewModel
上有一个属性,类型为IDictionary<string, string>
。 I am going through the list of properties on that ViewModel
and using reflection to determine if it is a dictionary. 我正在浏览该
ViewModel
的属性列表,并使用反射来确定它是否是字典。
Currently I have: 目前我有:
if (typeof(IDictionary).IsAssignableFrom(propDescriptor.PropertyType))
However, that is always false because propDescriptor.PropertyType
is IDictionary`2
. 但是,这总是错误的,因为
propDescriptor.PropertyType
是IDictionary`2
。 Any ideas how I can get that to work? 有什么想法可以使我工作吗? Also, why isn't that working?
另外,为什么这样不起作用?
I just changed my property to be IDictionary instead of IDictionary. 我只是将属性更改为IDictionary,而不是IDictionary。
EDIT: Not sure where my generics went, but the second IDictionary in the sentence above has string, string. 编辑:不知道我的泛型去了哪里,但是上面句子中的第二个IDictionary有字符串,字符串。
The reason why it's not working is that the generic IDictionary<,>
interface does not have the non-generic IDictionary
as a base interface. 它不起作用的原因是通用
IDictionary<,>
接口没有以非通用IDictionary
作为基本接口。
Maybe this is what you want: 也许这就是您想要的:
var type = propDescriptor.PropertyType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>))
{ // ...
Edit: The above code will only check if type
is declared as IDictionary<X, Y>
for some X
and Y
. 编辑:上面的代码将仅检查是否将某些
X
和Y
type
声明为IDictionary<X, Y>
。 If you also want to handle cases where type
represents a class or struct that implements IDictionary<X, Y>
(or even an interface derived from IDictionary<X, Y>
), then try this: 如果您还想处理
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))
{ // ..
It's not IDictionary`2
. 这不是
IDictionary`2
。 It's the compiler-generated class name for a generic IDictionary<TKey,TValue>
, which is not directly castable to an IDictionary
. 这是通用
IDictionary<TKey,TValue>
的编译器生成的类名,该类名不能直接转换为IDictionary
。
IDictionary`2
is not derived from IDictionary
as can be seen in its definition: IDictionary`2
不是从IDictionary
派生的,可以从其定义中看出:
public interface IDictionary<TKey, TValue> :
ICollection<KeyValuePair<TKey, TValue>>,
IEnumerable<KeyValuePair<TKey, TValue>>,
IEnumerable
Therefore the generic IDictionary<TKey, TValue>
is not castable to IDictionary
. 因此,通用
IDictionary<TKey, TValue>
不可转换为IDictionary
。
IDictionary is different from IDictionary< T, K > . IDictionary与IDictionary <T,K>不同 。
Use: 采用:
if (typeof(IDictionary<string, string>).IsAssignableFrom(propDescriptor.PropertyType))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.