gpt4 book ai didi

c# - 不能有两个具有相同签名但不同通用约束的方法

转载 作者:太空狗 更新时间:2023-10-29 23:12:54 25 4
gpt4 key购买 nike

我有这个方法:

public IEnumerable<MyType> DoSomething<TResult>(Func<MyType, TResult> func) 
where TResult : AnotherType

现在我希望此方法也出现在 IEnumerable<AnotherType> 中.所以我写了这个显然不能编译:

public IEnumerable<MyType> DoSomething<TResult>(Func<MyType, TResult> func) 
where TResult : IEnumerable<AnotherType>

我得到编译器错误:

Member with the same signature already declared

我读了Member with the same signature already defined with different type constraints它处理成员与另一种返回类型。然而,在我的示例中,我不区分方法返回类型,而是区分它的参数列表,即 Func<MyType, TResult>。首先和Func<IEnumerable<MyType>, TResult>在第二个。然而编译器无法处理这个。

除了为第二个示例使用另一个方法名称之外,还有其他方法吗?

最佳答案

确实不允许两个方法重载仅因泛型约束而不同。

在你的情况下,我想知道你是否需要 TResult (正如 Alfie Goodacre 所评论的那样)因为 IEnumerable<out T>T 中是协变的和 Func<in T1, out TResult>TResult 中是协变的.

所以尝试:

public IEnumerable<MyType> DoSomething(Func<MyType, AnotherType> func) 

和:

public IEnumerable<MyType> DoSomething(Func<MyType, IEnumerable<AnotherType>> func) 

由于提到的协方差,使用比 AnotherType 更派生的类会很好调用上述重载时。


另一种选择:

public IEnumerable<MyType> DoSomething<TResult>(Func<MyType, TResult> func) 
where TResult : AnotherType

和:

public IEnumerable<MyType> DoSomething<TResult>(Func<MyType, IEnumerable<TResult>> func) 
where TResult : AnotherType

在这种替代方法中,两个重载中的签名不同且约束相同。即使 AnotherType 这也可以工作是一个 interfaceTResultstruct (值类型)实现接口(interface),协方差(out Tout TResult)不起作用的情况。

关于c# - 不能有两个具有相同签名但不同通用约束的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41259074/

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