gpt4 book ai didi

c# - 不能在 IEnumerable 中使用对泛型类型的约束?

转载 作者:太空狗 更新时间:2023-10-29 23:06:28 24 4
gpt4 key购买 nike

可能已经有关于此的问题,但我无法想出搜索词来找到答案..

我可能在这里遗漏了一些明显的东西,但为什么不允许我执行以下操作,这会导致错误:

"Argument 1: cannot convert from System.Collections.Generic.IEnumerable<TType> to System.Collections.Generic.IEnumerable< Test.A>"

在调用 DoSomething 时?

public interface A
{
void Foo();
}

public class B : A
{
public void Foo()
{
}
}

class Test<TType> where TType : A
{
public Test(IEnumerable<TType> testTypes)
{
DoSomething(testTypes);
}

void DoSomething(IEnumerable<A> someAs)
{
}
}

当然,这样做是可以的:

class Test
{
public Test(IEnumerable<B> testTypes)
{
DoSomething(testTypes);
}

void DoSomething(IEnumerable<A> someAs)
{
}
}

最佳答案

变体仅适用于引用类型。在您的代码中,TType 也可以是值类型。如果添加 class 约束,代码将编译

class Test<TType> where TType : class, A
{
public Test(IEnumerable<TType> testTypes)
{
DoSomething(testTypes);
}

void DoSomething(IEnumerable<A> someAs)
{
}
}

可以找到详细的解释here

关于c# - 不能在 IEnumerable 中使用对泛型类型的约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32937055/

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