对Action< T>的模糊调用其中T继承具有相同方法签名的2个接口

编程入门 行业动态 更新时间:2024-10-10 14:23:13
本文介绍了对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个接口

本文发布于:2023-11-09 08:06:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571825.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模糊   接口   方法   amp   Action

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!