Extension method on lambda expression

元气小坏坏 提交于 2019-12-23 16:33:57

问题


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'

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?


回答1:


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).

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();



回答2:


you may create an extension method on an Action at the low cost of having a introducing instantiation. I sometimes use it and the code is readable. The reason this code exists is less elegant, a rotten NAS :-[

new Action(() =>
    {
        if (File.Exists(newFullPath))
            File.Delete(newFullPath);

        File.Move(oldFullPath, newFullPath);
    })
.Try(attemps: 2, exceptionValidator: (exception, attempt, attempts) =>
    {
        var throwIt = (attempt == attempts);
        if (!throwIt)
            Thread.Sleep(500);

        // .. tracing ./. throw
        return (throwIt);
    });

Just in case ... even if post not young.



来源:https://stackoverflow.com/questions/16328231/extension-method-on-lambda-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!