gpt4 book ai didi

c# - 为什么不能将受约束的开放泛型类型转换为受约束的类型?

转载 作者:太空狗 更新时间:2023-10-29 22:20:49 26 4
gpt4 key购买 nike

我想我一定遗漏了什么,为什么我不能编译这个:

class Foo<T> where T : Bar
{
T Bar;
}

abstract class Bar
{ }

class MyBar : Bar
{ }

static void Main(string[] args)
{
var fooMyBar = new Foo<MyBar>();
AddMoreFoos(fooMyBar);
}

static void AddMoreFoos<T>(Foo<T> FooToAdd) where T : Bar
{
var listOfFoos = new List<Foo<Bar>>();
listOfFoos.Add(FooToAdd); //Doesn't compile
listOfFoos.Add((Foo<Bar>)FooToAdd); //doesn't compile
}

最佳答案

在这里使用列表会让事情变得比他们需要的更困惑……这样最容易看到效果:

// This won't compile
Foo<Bar> fooBar = new Foo<MyBar>();

鉴于这无法编译,因此您无法添加 Foo<MyBar> 也就不足为奇了。到 List<Foo<Bar>>

那么为什么不是 Foo<MyBar>一个Foo<Bar> ?因为泛型类不是协变的。

泛型变体仅在 C# 4 中引入 - 它仅适用于接口(interface)和委托(delegate)。所以你可以(在 C# 4 中)做:

IEnumerable<MyBar> x = new List<MyBar>();
IEnumerable<Bar> y = x;

但你做不到:

IList<MyBar> x = new List<MyBar>();
IList<Bar> y = x;

我有一个关于方差的完整讨论,你可以从 NDC 2010 video site 下载- 只需搜索“方差”。

关于c# - 为什么不能将受约束的开放泛型类型转换为受约束的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3171855/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com