我有以下代码:
public class MyClass { public void MyMethod() { Action<Child> aFoo = a => a.Foo(); } } interface Parent1 { void Foo(); } interface Parent2 { void Foo(); } interface Child : Parent1, Parent2 { }然而,编译器告诉我,我在 aFoo 上有一个模糊的调用。
However, the compiler tells me that I have an ambiguous call on aFoo.
我试图执行 Action< Child> aFoo =(A a)=> a.Foo(); ,但它告诉我,我不能将lambda表达式转换为委托类型 System.Action< Child>
I tried to do Action<Child> aFoo = (A a) => a.Foo(); but it tells me that I cannot convert lambda expression to delegate type System.Action<Child>
如何解决歧义的错误?
推荐答案通过将值 a 在lambda的主体内:
By casting the value of a inside the body of the lambda:
Action<Child> aFoo = a => ((Parent1)a).Foo();您尝试的解决方案没有起作用,因为它完全还有其他功能:它试图适应一个使用 Child 的委托中的 Parent1 这是不可能的,即使它可以适应一个委托,将 Parent1 code> Child :
Your attempted solution did not work because it did something else entirely: it tried to fit a lambda expression taking a Parent1 into a delegate taking a Child. This is not possible, even though it is possible to fit a delegate taking a Parent1 into a delegate taking a Child:
Action<Child> aFoo = (Action<Parent1>)(a => a.Foo());后一种用法是可行的,因为 Action< T> 与T类型相反。
This latter usage is viable because Action<T> is contravariant on the type T.
更多推荐
对Action< T>的模糊调用其中T继承具有相同方法签名的2个接口
发布评论