gpt4 book ai didi

C# 用泛型重载 : bug or feature?

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

让我们举一个简单的例子:

void Foo<T>(IEnumerable<T> collection, params T[] items) 
{
// ...
}

void Foo<C, T>(C collection, T item)
where C : ICollection<T>
{
// ...
}

void Main()
{
Foo((IEnumerable<int>)new[] { 1 }, 2);
}

编译器说:

The type 'System.Collections.Generic.IEnumerable' cannot be used as type parameter 'C' in the generic type or method 'UserQuery.Foo(C, T)'. There is no implicit reference conversion from 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.ICollection'.

如果我将 Main 更改为:

void Main()
{
Foo<int>((IEnumerable<int>)new[] { 1 }, 2);
}

它会正常工作。为什么编译器不选择正确的重载?

最佳答案

我的猜测是编译器在使用通用约束之前会选择最佳匹配。在您的示例中,带有约束的方法更可取,因为它没有 params 最后一个参数。

编辑 - Eric Lippert 在他的回答中证实了这一点。

关于C# 用泛型重载 : bug or feature?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2586666/

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