C# .NET 中使用 Lambda 进行的不明确调用
我有一个带有重载方法的类:
MyClass.DoThis(Action<Foo> action);
MyClass.DoThis(Action<Bar> action);
我想将 lambda 表达式传递给 Action 版本:
MyClass.DoThis( foo => foo.DoSomething() );
不幸的是,Visual Studio 无法区分 Action
和 Action
版本,由于围绕“foo”变量的类型推断 - 因此它会引发编译器错误:
以下方法或属性之间的调用不明确:“MyClass.DoThis(System.Action
)”和“MyClass.DoThis(System.Action
)'
” ;
解决这个问题的最佳方法是什么?
I have a class with an overloaded method:
MyClass.DoThis(Action<Foo> action);
MyClass.DoThis(Action<Bar> action);
I want to pass a lambda expression to the Action version:
MyClass.DoThis( foo => foo.DoSomething() );
Unfortunately, Visual Studio rightly cannot tell the difference between the Action<Foo>
and Action<Bar>
versions, due to the type inference surrounding the "foo" variable -- and so it raises a compiler error:
The call is ambiguous between the following methods or properties: 'MyClass.DoThis(System.Action
<Foo>
)' and 'MyClass.DoThis(System.Action<Bar>
)'
What's the best way to get around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编译器无法自行解决这一问题。该调用确实不明确,您必须以某种方式澄清您想要编译器的重载。参数名称“foo”在重载决策中并不重要。
There's no way the compiler could figure that out by itself. The call is indeed ambiguous and you'll have to somehow clarify the overload you want for the compiler. The parameter name "foo" is insignificant here in the overload resolution.
我知道的方法是使用旧式委托:
这比 lambda 冗长得多。我还担心如果 yoiu 想要表达式树,它可能不起作用,尽管我对此不确定。
The way I know is to use an old-style delegate:
This is a lot more verbose than a lambda. I'm also concerned that it may not be work if yoiu want an expression trees, though I'm not sure about this.