Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

c# - Difference in CSC and Roslyn compiler's static lambda expression evaluation?

Consider the following example code.

class Program
{
    static void Main( string[] args )
    {
        DoSomethingWithAction( i =>
            {
                Console.WriteLine( "Value: {0}", i );
            } );

        Console.ReadLine();
    }

    private static void DoSomethingWithAction( Action<int> something )
    {
        Console.WriteLine( something.Target == null
            ? "Method is static."
            : "Method is not static." );

        something( 5 );
    }
}

If I compile and run this code under Debug using the Visual Studio 2010 (under CSC compiler) it will print out the following result:

Method is not static.
Value: 5

If I compile the same code in Visual Studio 2010, but this time using Release settings, the following output will be generated:

Method is static.
Value: 5

Now, if we were to execute the same code but this time using Visual Studio 2015 CTP (under the Roslyn compiler), the following output is generated for both Debug and Release settings:

Method is not static.
Value: 5

First, I find it curious that there is a difference between the Debug and Release versions of VS2010 (CSC). Why would it not evaluate as a static method under debug? Also, it appears that under some cases it does evaluate as static when compiled in Debug. I have a production application that is getting the expected static result under Debug.

Secondly, should the Roslyn compiler match the behavior of CSC in this particular case?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This was a deliberate change made by the Roslyn team.

Delegates that point to instance methods are slightly faster to invoke, so Roslyn now compiles lambdas to instance methods even when it doesn't need to.

See discussion.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...