[英]Why My Code doesn't support Co-variant Interface?
According To reflector , ExpandoObject Does implemenet IDictionary<string, object>
根据反射器,ExpandoObject确实实现
IDictionary<string, object>
How ever I have this code which i dont understand why Does Interface co-variance doesn't work here 我怎么有这段代码,我不明白为什么接口协方差在这里不起作用
From what Ive read - it does suppose to work : 从我读过的书-它确实可以工作:
There are three things wrong here: 这里有三件事是错误的:
IDictionary<TKey, TValue>
is invariant in both its type parameters IDictionary<TKey, TValue>
在两个类型参数中都是不变的 int
here) int
) You should ignore the dynamic
part here - it's a red herring. 您应该在这里忽略
dynamic
部分-这是一条红色鲱鱼。 Try working out some code you'd expect to work that doesn't use dynamic
. 尝试编写一些您期望使用的代码,这些代码不使用
dynamic
。 Here's an example of why IDictionary<,>
is invariant: 这是为什么
IDictionary<,>
不变的示例:
// Suppose it were covariant in value...
Dictionary<string, string> stringToString = new Dictionary<string, string>();
IDictionary<string, object> stringToObject = stringToString;
stringToObject["foo"] = new MemoryStream();
string value = stringToString["foo"]; // Um?
// Suppose it were contravariant in value...
Dictionary<string, object> stringToObject = new Dictionary<string, object>();
IDictionary<string, string> stringToString = stringToString;
stringToObject["foo"] = new MemoryStream();
string value = stringToString["foo"]; // Um?
IDictionary<TKey,TValue>
does not support any variance. IDictionary<TKey,TValue>
不支持任何差异。 IDictionary<string,object>
to IDictionary<string,int>
: IDictionary<string,object>
转换为IDictionary<string,int>
会发生什么: int
. int
。 But since you can add arbitrary objects to it, it can't actually ensure that guarantee. int
is no reference type. int
是没有引用类型。 IDictionary<string,object>
to IDictionary<string,int>
. IDictionary<string,object>
的类转换为IDictionary<string,int>
。 No matter if you use static casting or dynamic.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.