gpt4 book ai didi

c# - 为什么 Roslyn 在这里生成 > 比较而不是 != 比较?

转载 作者:太空狗 更新时间:2023-10-29 20:07:02 25 4
gpt4 key购买 nike

我最近在尝试使用 TryRoslyn 上的 C# 编译器时遇到了一个奇怪的问题,即不等式检查被转换为大于检查。这是重现代码:

using System;
public class C {
public void M() {
if (Foo() != 0 || Foo() != 0)
{
Console.WriteLine("Hi!");
}
}

private int Foo() => 0;
}

下面是反编译器生成的代码:

using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
[assembly: AssemblyVersion("0.0.0.0")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[module: UnverifiableCode]
public class C
{
public void M()
{
bool flag = this.Foo() != 0 || this.Foo() > 0; // this should be an != check
if (flag)
{
Console.WriteLine("Hi!");
}
}
private int Foo()
{
return 0;
}
}

Here's复制品的链接。为什么 Roslyn 这样做;是bug吗?

我在玩了一段时间代码后做出的一些观察:

  • 这只会发生在条件中的最后一个 bool 表达式上。例如,如果您添加另一个 || 语句,它只会在最后一次调用 Foo() 时发生。

  • 它也只发生在 0 上,特别是;如果将其替换为 1 或其他一些数字,则不会发生这种情况。

最佳答案

反编译代码错误;这是反编译器中的错误,而不是编译器中的错误。生成的 IL 是正确的。 仔细阅读 IL。明白为什么大于比较是正确的,反编译是错误的吗?

至于为什么这个代码生成只发生在运算符的右侧,我不记得了。如果你想在代码生成器中探索它,就在这里:

https://github.com/dotnet/roslyn/blob/master/src/Compilers/CSharp/Portable/CodeGen/EmitOperators.cs

您需要方法 EmitIsNonNullOrZero

关于c# - 为什么 Roslyn 在这里生成 > 比较而不是 != 比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37693205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com