lambda表达式的扩展方法 [英] Extension method on lambda expression
问题描述
我有一个辅助方法,该方法获取由lambda定义的属性的名称,该属性的工作方式如下:
I have a helper method which gets the name of a property defined by a lambda which works as below:
ExpressionUtil.GetName((Thing t) => t.Property); // returns "Property"
我想将其转换为扩展方法,以便语法采用以下形式:
I would like to turn this into an extension method so the syntax would be of the form:
((Thing t) => t.Property).GetName(); // wont compile : operator '.' cannot be applies to operand of type 'lambda expression'
但是我似乎无法做到这一点,因为((Thing t) => t.Property)
是lambda(还不是表达式或Func).有什么方法可以编写直接适用于lambda的扩展方法?如果不是,那这是一件不好的事吗?
However I cant seem to do this as ((Thing t) => t.Property)
is a lambda (not an expression or Func yet). Is there any way to write an extension method which applies directly to a lambda? If not why is this a bad thing to do?
推荐答案
您不能这样做,因为lambda表达式本身没有类型.它的类型由上下文决定(例如,如果将其分配给委托变量或将其作为方法的参数传递给该变量).
You can't do that, because a lambda expression has no type by itself; its type is determined by the context (e.g. if you assign it to a delegate variable or pass it as an argument to a method).
由于((Thing t) => t.Property)
没有类型,因此您不能在其上调用扩展方法,因为编译器不知道哪些扩展方法是有效的候选方法.
Since ((Thing t) => t.Property)
doesn't have a type, you can't call an extension method on it, because the compiler doesn't know which extension methods are valid candidates.
但是,您可以声明一个变量并在其上调用扩展方法:
You can, however, declare a variable and call the extension method on it:
Func<Thing, OtherThing> func = t => t.Property;
string name = func.GetName();
这篇关于lambda表达式的扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!