简体   繁体   中英

Extension method on lambda expression

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?

You can't do that, because a lambda expression has no type by itself; its type is determined by the context (eg 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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM