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

前端 未结 3 622
借酒劲吻你
借酒劲吻你 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条回答
  •  Happy的楠姐
    2020-12-14 06:54

    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 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

提交回复
热议问题