为了探索 C# 编译器如何优化代码,我创建了一个简单的测试应用程序。每次测试更改时,我都会编译应用程序,然后在 ILSpy 中打开二进制文件。
我刚刚注意到一些对我来说很奇怪的东西。显然这是故意的,但是,我想不出编译器会这样做的充分理由。
考虑以下代码:
static void Main(string[] args)
{
int test_1 = 1;
int test_2 = 0;
int test_3 = 0;
if (test_1 == 1) Console.Write(1);
else if (test_2 == 1) Console.Write(1);
else if (test_3 == 1) Console.Write(2);
else Console.Write("x");
}
毫无意义的代码,但我写这个是为了看看 ILSpy 将如何解释这些if
语句。
然而,当我编译/反编译这段代码时,我确实注意到了一些让我摸不着头脑的东西。我的第一个变量test_1
被优化为test_
!C# 编译器这样做有充分的理由吗?
为了全面检查,这是Main()
我在 ILSpy 中看到的输出。
private static void Main(string[] args)
{
int test_ = 1; //Where did the "1" go at the end of the variable name???
int test_2 = 0;
int test_3 = 0;
if (test_ == 1)
{
Console.Write(1);
}
else
{
if (test_2 == 1)
{
Console.Write(1);
}
else
{
if (test_3 == 1)
{
Console.Write(2);
}
else
{
Console.Write("x");
}
}
}
}
更新
显然,在检查了 IL 之后,这是 ILSpy 的问题,而不是 C# 编译器的问题。Eugene Podskal 对我最初的评论和观察给出了很好的回答。但是,我很想知道这是否是 ILSpy 中的一个错误,或者这是否是故意的功能。