[英]Unable to cast constrained generic interface reference to covariant interface reference
我试图了解协方差如何与泛型类型约束一起工作,并且似乎没有明显的原因忽略了约束。
考虑以下代码:
public interface IContainer<out T> { }
public interface IContents { }
public class Food : IContents { }
public class Foo
{
public void Bar<T>() where T : IContents
{
IContainer<IContents> x = null;
IContainer<T> y = null;
IContainer<Food> z = null;
x = y; // Cannot convert source type 'IContainer<T>' to target type 'IContainer<IContents>'
x = z; // Valid
}
}
为什么编译器会在x = y
上产生“无法转换”错误而在x = z
上没有产生错误?
C# 不支持值类型的变体 - 来自变体泛型接口文档:
C# 中的
ref
、in
和out
参数不能是变体。 值类型也不支持方差。
即下一个将不起作用:
public struct MyStruct : IContents
{
}
var structContainer = (IContainer<MyStruct>)null;
IContainer<IContents> x = structContainer;
由于T
既不受class
也不受struct
限制,它可以是引用类型或值类型,所以在一般情况下IContainer<T>
不能分配给IContainer<IContents>
。
为Bar
方法添加class
约束:
public class Foo
{
public void Bar<T>() where T : class, IContents
{
IContainer<IContents> x = null;
IContainer<T> y = null;
IContainer<Food> z = null;
x = y; // Now Valid
x = z; // Valid
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.