gpt4 book ai didi

c# - 为什么我必须转换为类型参数而不能使用受约束的类型?

转载 作者:太空宇宙 更新时间:2023-11-03 19:08:38 25 4
gpt4 key购买 nike

谁能解释为什么我必须转换为 T 以及为什么 Add2 不接受 Bar 作为参数?

class Foo<T> where T : class, IBar
{
void Add1(IDo<T> @do) { @do.Stuff(new Bar() as T); }

// Add2 does not compile:
// Argument type Bar is not assignable to parameter Type T
void Add2(IDo<T> @do) { @do.Stuff(new Bar()); }
}

interface IBar {}

class Bar : IBar {}

interface IDo<in T> {
void Stuff(T bar);
}

最佳答案

可能不合适。例如,考虑:

class Other : Bar {}

...

IDo<Other> do = new DoImpl<Other>();
Foo<Other> foo = new Foo<Other>();
foo.Add2(do);

使用您当前的代码,将调用 do.Add2(new Bar()) ... 这显然是无效的 Bar不是 Other , IDo<Other>.Stuff 要求.

转换为 T (或使用 as )也不合适 - 你不能投 new Bar()Other , 如果你使用 as你只会得到一个空引用。

关于c# - 为什么我必须转换为类型参数而不能使用受约束的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23292117/

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