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

杀马特。学长 韩版系。学妹 提交于 2019-11-28 20:12:42
Rob

I don't have an answer as to why that is so (reproduced locally, too).

However, the answer to:

Why is it so? How can this be avoided so that Expression.Call would begin to work again in new Visual Studio?

You can do this (works on both compilers):

Action<int, int> a = (x, y) => Console.WriteLine(x + y);

ParameterExpression p1 = Expression.Parameter(typeof(int), "p1");
ParameterExpression p2 = Expression.Parameter(typeof(int), "p2");

MethodCallExpression call;
if (a.Method.IsStatic)
{
    call = Expression.Call(a.Method, p1, p2);
}
else
{
    call = Expression.Call(Expression.Constant(a.Target), a.Method, p1, p2);
}

Thanks to Jeppe Stig Nielsen for fix regarding a.Target

Peter O.

Roslyn (the C# compiler used by VS 2015) changed all lambda methods to non-static methods, whether they capture variables or not. See Delegate caching behavior changes in Roslyn. As I explain, this is an allowed behavior because anonymous methods (like those at issue here) that don't capture variables have fewer lifetime requirements than those that do. This doesn't mean, though, that those methods must be static: this is merely an implementation detail.

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<int, int> <>9__0_0;

        static <>c()
        {
            Program.<>c.<>9 = new Program.<>c();
        }

        internal void <Main>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.

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