Why has a lambda with no capture changed from a static in C# 5 to an instance method in C# 6?

前端 未结 3 620
借酒劲吻你
借酒劲吻你 2020-12-14 06:12

This code throws an exception on the marked line:

using System;
using System.Linq.Expressions;

namespace ConsoleApplication2
{
    class Program
    {
              


        
3条回答
  •  执笔经年
    2020-12-14 07:02

    Why is it so?

    I don't know why, and honestly was unaware of that change, but taking a quick look at the decompiled code showed that for all similar lambdas inside the class Roslyn generates instance methods in a singleton nested class called <>c like this

    internal class Program
    {
        [CompilerGenerated]
        [Serializable]
        private sealed class <>c
        {
            public static readonly Program.<>c <>9;
            public static Action <>9__0_0;
    
            static <>c()
            {
                Program.<>c.<>9 = new Program.<>c();
            }
    
            internal void 
    b__0_0(int x, int y) { Console.WriteLine(x + y); } } }

    To me this is a breaking change, but I didn't find any information about that.

    What about how to make your code working, I think @Rob answer covers that part.

提交回复
热议问题