c# - C# 中的 if (string) 与 if (bool)

标签 c# if-statement boolean compare

如果在“if”开头使用字符串而不是 boolean 值进行比较,性能/代码质量是否有明显差异?

字符串示例:

string isTrue = "true";
if (isTrue == "true"){
  // do something
}

boolean 示例:

bool isTrue = true;
if (isTrue){
   //do something
}

我通常使用 boolean 值进行此类比较,但我在网上看到了这两种变体。

最佳答案

基于 tryroslyn 上生成的代码

代码:

using System;
public class C {
    public void M() {
        string isStringTrue = "true";
        if (isStringTrue == "true")
        {
            // do something
        }              

        bool isBoolTrue = true;
        if (isBoolTrue)
        {
            //do something
        }
    }
}

生成 IL 代码:

.class private auto ansi '<Module>'
{
} // end of class <Module>

.class public auto ansi beforefieldinit C
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig 
        instance void M () cil managed 
    {
        // Method begins at RVA 0x2050
        // Code size 34 (0x22)
        .maxstack 2
        .locals init (
            [0] string,
            [1] bool,
            [2] bool,
            [3] bool
        )

        IL_0000: nop
        IL_0001: ldstr "true"
        IL_0006: stloc.0
        IL_0007: ldloc.0
        IL_0008: ldstr "true"
        IL_000d: call bool [mscorlib]System.String::op_Equality(string, string)
        IL_0012: stloc.2
        IL_0013: ldloc.2
        IL_0014: brfalse.s IL_0018
        IL_0016: nop
        IL_0017: nop
        IL_0018: ldc.i4.1
        IL_0019: stloc.1
        IL_001a: ldloc.1
        IL_001b: stloc.3
        IL_001c: ldloc.3
        IL_001d: brfalse.s IL_0021
        IL_001f: nop
        IL_0020: nop
        IL_0021: ret
    } // end of method C::M

    .method public hidebysig specialname rtspecialname 
        instance void .ctor () cil managed 
    {
        // Method begins at RVA 0x207e
        // Code size 8 (0x8)
        .maxstack 8

        IL_0000: ldarg.0
        IL_0001: call instance void [mscorlib]System.Object::.ctor()
        IL_0006: nop
        IL_0007: ret
    } // end of method C::.ctor

} // end of class C

如你所见,比较字符串需要调用方法,比较 boolean 不需要这个。

关于c# - C# 中的 if (string) 与 if (bool),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39721266/

相关文章:

c# - 统一解析嵌套的json

c# - 将两个或多个 Crystal Reports 合并为一个 PDF

c++ - if else 语句混淆了 c++

ios - 从 Objective-C 中的 ColdFusion boolean 返回类型获取 BOOL 的更好方法?

c# - 命名空间 System.Configuration 中不存在 configurationManager

c++ - 没有内部作用域的 if 语句?

ios - 使用或 || if 语句中的运算符以评估变量(不等于两(2)个字符串)

java - Android 比较 boolean 值

java - Java中的随机 boolean 二维数组总是返回 "false"

c# - 如何在 Linux 中的 C# 中将图标插入单声道应用程序