我有这个方法:
public IEnumerable<MyType> DoSomething<TResult>(Func<MyType, TResult> func)
where TResult : AnotherType
Run Code Online (Sandbox Code Playgroud)
现在我想要这个方法也出现了IEnumerable<AnotherType>.所以我写了这个,显然没有编译:
public IEnumerable<MyType> DoSomething<TResult>(Func<MyType, TResult> func)
where TResult : IEnumerable<AnotherType>
Run Code Online (Sandbox Code Playgroud)
我得到编译器错误:
已经声明具有相同签名的成员
我读了具有相同签名的成员,该签名已经定义了不同的类型约束,它们使用另一个返回类型处理成员 但是在我的例子中,我没有区分方法return-type,而是在它的param-list中,它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)
Run Code Online (Sandbox Code Playgroud)
和:
public IEnumerable<MyType> DoSomething(Func<MyType, IEnumerable<AnotherType>> func)
Run Code Online (Sandbox Code Playgroud)
由于上面提到的协方差,使用比AnotherType调用上述重载时派生的类更好.
另外一个选项:
public IEnumerable<MyType> DoSomething<TResult>(Func<MyType, TResult> func)
where TResult : AnotherType
Run Code Online (Sandbox Code Playgroud)
和:
public IEnumerable<MyType> DoSomething<TResult>(Func<MyType, IEnumerable<TResult>> func)
where TResult : AnotherType
Run Code Online (Sandbox Code Playgroud)
在这种替代方法中,签名不同,并且两个过载中的约束相同.这可以工作,即使AnotherType是interface和实现接口TResult的struct(值类型),协方差(out T和out TResult)不起作用的情况.