【发布时间】:2017-06-14 19:40:19
【问题描述】:
假设我有以下程序:
static void SomeMethod(Func<int, int> otherMethod)
{
otherMethod(1);
}
static int OtherMethod(int x)
{
return x;
}
static void Main(string[] args)
{
SomeMethod(OtherMethod);
SomeMethod(x => OtherMethod(x));
SomeMethod(x => OtherMethod(x));
}
我无法理解编译后的 il 代码(它使用了太多额外的代码)。这是简化版:
class C
{
public static C c;
public static Func<int, int> foo;
public static Func<int, int> foo1;
static C()
{
c = new C();
}
C(){}
public int b(int x)
{
return OtherMethod(x);
}
public int b1(int x)
{
return OtherMethod(x);
}
}
static void Main()
{
SomeMethod(new Func<int, int>(OtherMethod));
if (C.foo != null)
SomeMethod(C.foo)
else
{
C.foo = new Func<int, int>(c, C.b)
SomeMethod(C.foo);
}
if (C.foo1 != null)
SomeMethod(C.foo1)
else
{
C.foo1 = new Func<int, int>(c, C.b1)
SomeMethod(C.foo1);
}
}
为什么编译器创建非静态相等方法b/b1?相等意味着它们具有相同的代码
【问题讨论】:
-
SomeMethod(x => OtherMethod(x));也有 1
-
@becike,是的,当然。我同意你的看法。但实现似乎很奇怪
-
否则我不确定你想要什么,因为这段代码没有编译,所以你错过了几部分
-
@becike,我认为编译后的代码版本不会包含
b1方法 - 这是主要问题
标签: c# clr compiler-optimization