在 lambda 表达式上调用方法而不需要变量声明
考虑到这种扩展方法,
public static void Until(this Action action, Func<bool> booleanFunc)
{
while (!booleanFunc())
action();
}
是否有可能将其变成
var x = 0;
Action ac = () => x += 1;
ac.Until(() => x == 5);
这种类型的东西
var x = 0;
(() => x += 1).Until(() => x == 5);
,即单行?
Given this extension method
public static void Until(this Action action, Func<bool> booleanFunc)
{
while (!booleanFunc())
action();
}
is it possible to turn this
var x = 0;
Action ac = () => x += 1;
ac.Until(() => x == 5);
into something of this sort
var x = 0;
(() => x += 1).Until(() => x == 5);
That is, a one liner?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那么 lambda 需要一个类型。说
() =>; x += 1
本身并没有说明它应该代表的委托。因此,通过将 lambda 传递给构造函数来提供它的类型。演员阵容也能发挥作用。
Well lambdas need a type. Saying
() => x += 1
alone says nothing about the delegate it is supposed to represent. So provide the type of the lambda by passing it into the constructor.A cast works as well.
不幸的是,这种语法是不可能的,因为编译器无法推断匿名表达式的类型。它可以是 Action,但也可以是其他一些自定义的委托。您需要将其转换为
Action
。Unfortunately such syntax is not possible because the compiler cannot infer the type of the anonymous expression. It could be Action but it also could be some other custom defined delegate. You will need to cast it to
Action
.这很有趣 - 我 不久前发现了同样的事情。
扩展方法调用在 C# 规范的第 7.6.5.2 节中进行了描述,在我看来,所有条件都已满足...因为这涉及到可隐式转换为第一个参数类型的表达式(它是是,在这种情况下)。这表明编译器中存在错误(可能,但不太可能),或者不满足有效方法调用的早期条件之一。
我怀疑问题在于 lambda 表达式不是规范术语中的主要表达式 - 不幸的是,由于感冒,我的规范 fu 今天早上表现不佳。方法调用机制的许多其余部分可能依赖于了解方法目标的类型,在本例中这是未知的。
请注意,另一个明显的“无类型表达式”也有同样的问题 - 您也无法在
null
文字上调用扩展方法。偶尔这个限制是一个痛苦,但大多数时候我对此没有太大问题 - 而且我怀疑它使编译器更容易实现......
It's interesting - I discovered the same thing a while ago.
Extension method invocations are described in section 7.6.5.2 of the C# spec, and it seems to me that all of the conditions there are met... because that talks in terms of an expression being implicitly convertible to the first parameter type (which it is, in this case). That suggests that either there's a bug in the compiler (possible, but unlikely) or that one of the earlier conditions for it being a valid method call isn't met.
I suspect the problem is that a lambda expression isn't a primary-expression in spec terminology - unfortunately, my spec-fu isn't up to much this morning due to a cold. A lot of the rest of the method invocation machinery probably relies on knowing the type of the target of the method, which isn't known in this case.
Note that the other conspicuous "untyped expression" has the same problem - you can't call extension methods on a
null
literal, either.Very occasionally this limitation is a pain, but most of the time I don't have much of an issue with it - and I suspect it makes the compiler a lot simpler to implement...