using System;
class X {}
class Y: X {}
class Wrapper<T> where T : X {}
public class HelloWorld
{
public static void Main(string[] args)
{
Wrapper<Y> y = new();
Wrapper<X> x = y; // Error here
}
}
错误是
error CS0029: Cannot implicitly convert type 'Wrapper<Y>' to 'Wrapper<X>'
这里我想把
Wrapper<Y>
转换成Wrapper<X>
。
我该怎么做?
一般情况下你不能。考虑以下示例:
y
是 List<Y>
,x
是 List<X>
。这意味着执行 x.Add(new X())
应该是合法的(因为您可以使用 List<X>
来执行此操作),但如果它实际上是 List<Y>
,则这将是非法操作,因为 new X()
不是类型 Y
。反之亦然,因为这会破坏像 y[0]
这样的读取操作。这称为模板协变和逆变,您可以在here阅读更多相关信息