Lambda被视为罗斯林的封闭代表 [英] Lambda treated as a closed delegate in Roslyn
问题描述
我很惊讶这两个委托( fn1
和 fn2
)之间会存在运行时差异: / p>
I was surprised that there would be any runtime difference between these two delegates (fn1
and fn2
):
static int SomeStaticMethod(int x) { return x; }
// fn1.Target == null in this case
Func<int, int> fn1 = SomeStaticMethod;
// fn2.Target != null in this case
Func<int, int> fn2 = x => x;
但是显然第二个lambda被视为实例方法,因为它的 Target
属性为非null。在我切换到Visual Studio 2015之前,它的处理方式有所不同(在VS2012中,我很确定它被视为静态方法)。
But apparently the second lambda is treated like an instance method, because its Target
property is non-null. And it was treated differently before I switched to Visual Studio 2015 (in VS2012, I am pretty sure it was treated as a static method).
没有闭包的lambda在C#中被视为封闭的委托(即实例方法)?我以为可能是调试器添加了一些东西,但是它也发生在发行版中。
Is there a reason why a lambda with no closures is treated as a closed delegate (i.e. an instance method) in C#? I thought perhaps it's the debugger adding some stuff, but it also happens in release builds.
(澄清)
关键是,我有一个像这样的方法,它创建了一个通用委托来快速从枚举转换为整数(无装箱):
The point is, I had a method like this which created a generic delegate for quickly converting from enums to ints (without boxing):
private static Func<int, TEnum> CreateIntToEnumDelegate()
{
Func<int, int> lambda = x => x;
return Delegate.CreateDelegate(typeof(Func<int, TEnum>), lambda.Method)
as Func<int, TEnum>;
}
在罗斯林不再有效了,因为实例 lambda与委托人签名不兼容。因此,我不得不使用 static
方法,没什么大不了的。
and it didn't work in Roslyn anymore, because the "instance" lambda became incompatible with the delegate signature. So I had to use a static
method instead, no big deal.
但是让我担心的是,这在编译时是不可能发现的。 此线程描述了类似的问题,顺便说一句,现在我搜索了罗斯林代表 。
But what worries me is that this was impossible to catch during compile-time. This thread describes similar issues, btw, now that I searched for "Roslyn delegates".
推荐答案
这是 2014年对罗斯林进行的更改。确实很奇怪,但是实际上是为了改善性能 。 在新策略中,所有lambda都作为实例方法发出 -来自讨论在roslyn.codeplex.com (注意:无效链接)。
This was a change made to Roslyn in 2014. It is quite strange, but it was actually done to improve performance. "In the new strategy all lambdas are emitted as instance methods" - from the discussion at roslyn.codeplex.com (note: dead link).
这篇关于Lambda被视为罗斯林的封闭代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!