问题描述
我想知道为什么不能将 IEnumerable< int>
分配给 IEnumerable< object>
。毕竟 IEnumerable
是少数支持协方差的接口之一...
I wonder why IEnumerable<int>
can't be assigned to a IEnumerable<object>
. After all IEnumerable
is one of the few interfaces that supports covariance...
- 子类型关系和协方差材料适用于引用类型
-
int
似乎是object
- The subtype relation and covariance stuff works with reference types
int
seems to be a proper subtype ofobject
但这两个功能的组合不起作用...
The combination of both features doesn't work however...
class A
{
}
class B : A
{
}
class Program
{
static void Main(string[] args)
{
bool b;
b = typeof(IEnumerable<A>).IsAssignableFrom(typeof(List<B>));
Console.WriteLine("ienumerable of ref types is covariant: " + b); //true
b = typeof(IEnumerable<object>).IsAssignableFrom(typeof(List<int>));
Console.WriteLine("ienumerable of value tpyes is covariant: " + b); //false
b = typeof(object).IsAssignableFrom(typeof(int));
Console.WriteLine("int is a subtype of object: " + b); //true
}
}
感谢您的帮助!
sebastian
thanks for your help!sebastian
推荐答案
在将值类型装箱之前,它们不是对象的LSP子类型。
Value types aren't LSP-subtypes of object until they're boxed.
方差不适用于值类型。
Variance doesn't work with value types. At all.
说明 int
不是 object 的> proper子类型(在LSP中是子类型):
Demonstration that int
is not a proper subtype (subtype in the LSP sense) of object
:
作品:
object x = new object();
lock (x) { ... }
不起作用(违反了可替代性):
Does not work (substitutability violated):
int y = new int();
lock (y) { ... }
返回true:
object x = new object();
object a = x;
object b = x;
return ReferenceEquals(a, b);
返回假(违反可替代性):
Returns false (substitutability violated):
int y = new int();
object a = y;
object b = y;
return ReferenceEquals(a, b);
当然,问题的主题(界面变化)是第三次演示。
Of course, the topic of the question (interface variance) is a third demonstration.
这篇关于C#4.0:int对象的真正子类型?协方差,即数和值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!