如何在c#中的包装类泛型中转换派生类

问题描述 投票:0回答:1
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>

我该怎么做?

c# generics derived-class
1个回答
0
投票

一般情况下你不能。考虑以下示例:

y
List<Y>
x
List<X>
。这意味着执行
x.Add(new X())
应该是合法的(因为您可以使用
List<X>
来执行此操作),但如果它实际上是
List<Y>
,则这将是非法操作,因为
new X()
不是类型
 Y
。反之亦然,因为这会破坏像
y[0]
这样的读取操作。这称为模板协变和逆变,您可以在here

阅读更多相关信息
© www.soinside.com 2019 - 2024. All rights reserved.