为什么没有捕捉拉姆达从C#5静态更改为C#6的实例方法? [英] Why has a lambda with no capture changed from a static in C# 5 to an instance method in C# 6?
问题描述
此代码抛出的标记线异常:
This code throws an exception on the marked line:
using System;
using System.Linq.Expressions;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Action<int, int> a = (x, y) => Console.WriteLine(x + y);
ParameterExpression p1 = Expression.Parameter(typeof(int), "p1");
ParameterExpression p2 = Expression.Parameter(typeof(int), "p2");
// Here is the exception ArgumentNullException.
MethodCallExpression call = Expression.Call(a.Method, p1, p2);
}
}
}
现在,我测试过这段代码在VS2013(就像一个魅力)和VS2015共同体(罚球除外)。
Now, I've tested this code in VS2013 (works like a charm) and in VS2015 Community (throws the exception).
我跟着的。净参考源,害得我这checkes一些代码条件是否提供的方法 IsStatic
或没有。
I followed the .Net Reference Source, which led me to some code condition which checkes whether the supplied method IsStatic
or not.
在我的情况,我通过方法( a.Method
)在VS2013和VS2015中的某些原因的非静态(实例)是静态的。如果不是,它抛出,告诉我,我没有提供的实例
参数。
In my case, the method I pass (a.Method
) is static in VS2013 and for some reason non static (instance) in VS2015. If not, it throws, telling me that I did not supply the Instance
argument.
为什么会这样呢?这怎么能避免这样 Expression.Call
将开始在新的Visual Studio重新工作?
Why is it so? How can this be avoided so that Expression.Call
would begin to work again in new Visual Studio?
推荐答案
罗斯林(由2015年VS使用C#编译器)改变了所有的lambda方法,非静态方法,它们是否捕捉变量或没有。见罗斯林 代理缓存行为的变化。由于我解释,这是允许的行为,是因为不捕获变量匿名方法(如那些问题在这里)比那些做一辈子的要求较少。这并不意味着,虽然,这些方法必须是静态的:这仅仅是一个实施的细节
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.
这篇关于为什么没有捕捉拉姆达从C#5静态更改为C#6的实例方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!