简体   繁体   中英

Anonymous method in static class is non-static? How to invoke it?

I am running the following program on two different machines:

static class Program
{
    static void Main(string[] args)
    {
        Func<int> lambda = () => 5;
        Console.WriteLine(lambda.GetMethodInfo().IsStatic);
        Console.ReadLine();
    }        
}

On one machine, with .NET 4.5 and Visual Studio 2012 installed this prints "true", on another one, with .NET Framework 4.6.2 and Visual Studio 2015 it prints "false".

I thought that anonymous methods were static if they are defined in a static context. Did this change (in a documented way) during some of the last framework updates?

What I need to do, is to use Expression.Call on lambda.GetMethodInfo() , and in the non-static case this requires an instance on which the lambda is defined. If I wanted to use lambda.GetMethodInfo().Invoke I would face the same problem.

How can I get such an instance?

Bear in mind that this (lambdas) is a compiler feature so the runtime framework version won't make a difference. Also, because this is a compiler feature, it's not all that surprising that there's a difference between 2012 and 2015 (when Roslyn was introduced which replaced most of the existing compiler infrastructure).

I cannot give a solid reason for why it would have been specifically changed here (although I know several changes were made to enabled Edit-and-Continue to work in more contexts), but it has never been contractual about how lambdas are implemented.

How can I get such an instance?

Well, lambda is a Delegate , and that's always exposed a Target property which references an instance when the delegate is so bound.

How can I get such an instance

I am not sure it matters? Surely you can run the lambda function by simply doing this (for example)

Console.Print(lambda());

So the fact that it is static or not is largely immaterial.

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