对Action< T>的模糊调用其中T继承具有相同方法签名的2个接口 [英] Ambiguous call on an Action<T> where T inherits 2 interfaces having the same method signature

查看:146
本文介绍了对Action< T>的模糊调用其中T继承具有相同方法签名的2个接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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&lt; T&gt;的模糊调用其中T继承具有相同方法签名的2个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆