【发布时间】:2016-05-30 13:47:04
【问题描述】:
假设我有一个界面,例如
public interface IInterface<in TIn, out TOut> {
IInterface<TIn, TOut> DoSomething(TIn input);
}
TIn 是 contra-变体,TOut 是 co-变体。
现在,我希望调用者能够指定要在输入值上执行的某个函数,所以我会天真地将以下方法添加到接口中:
IInterface<TIn, TOut> DoSomethingWithFunc(Func<TIn, TOut> func);
哪个……不起作用。 TIn 现在需要是协变的,而TOut 是逆变的。
我明白,我不能使用协变泛型类型作为方法的输入,但我认为我可以在嵌套泛型类型中使用它们,该类型本身指定方差 (Func<in T1, out TResult>)。
我尝试使用协变/逆变类型创建新的委托类型,并更改接口以接受此类型的参数,但无济于事(同样的错误)。
public delegate TOut F<in TDlgIn, out TDlgOut>(TDlgIn input);
public interface IInterface<in TIn, out TOut> {
IInterface<TIn, TOut> DoSomethingWithFunc(F<TIn, TOut> func);
}
我有办法让编译器满意吗? 这是否可能(例如使用其他嵌套类型或其他泛型参数)?如果没有,为什么不呢?
【问题讨论】:
-
不确定this discussion 是否适用,但可能适用。
-
我想,这与我之前问过的一个问题有关:stackoverflow.com/questions/6126741/…
-
你试过
delegate TOut F<out TDlgIn, in TDlgOut>(TDlgIn input)吗?在传递代表时,协方差需要反过来。
标签: c# .net generics generic-variance