.net - 为什么 .NET Boolean 有 TrueLiteral 和 TrueString?

标签 .net refactoring types boolean

为什么在 boolean 类型中有两个字段具有相同的值?

internal const int True = 1;
internal const int False = 0;
internal const string TrueLiteral = "True";
internal const string FalseLiteral = "False";

public static readonly string TrueString;
public static readonly string FalseString;

static Boolean()
{
    TrueString = "True";
    FalseString = "False";
}

在反射器生成的代码中,方法不使用这些字符串,但是:

public string ToString(IFormatProvider provider)
{
    if (!this)
    {
        return "False";
    }
    return "True";
}

使用这些常量值不是更好吗?

编辑:在 CIL 中,使用常量字符串和实例字符串没有区别。

所以当我声明一个 private const string = "a"时,在应用程序中任何使用 "a"的地方,Jitter 都使用 const 值,还是仅在 const string 的范围内?

最佳答案

A quick synopsis on the differences between 'const' and 'readonly' in C#:

const:

  • Can't be static.
  • Value is evaluated at compile time.
  • Initiailized at declaration only.

readonly:

  • Can be either instance-level or static.
  • Value is evaluated at run time.
  • Can be initialized in declaration or by code in the constructor.

( source )

因此,在您看到“False”硬编码的地方,它只是在编译时从 FalseLiteral const 替换。

关于.net - 为什么 .NET Boolean 有 TrueLiteral 和 TrueString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2584224/

相关文章:

.net - 单击 mailto 链接后未加载 Outlook 插件

.net - c# .net core 2.1 系统环境变量控制台应用程序未加载

java - Web 应用程序的硬件支持

c++ - 类模板,允许用户定义类型 C++

c# - 使 Refit 自动在查询字符串中提供参数

c# - 十六进制输出中的扩展工具包的 NumericUpDown

c# - 重构速度 : Convert To a Date

c++ - 如何使这些测试用例代码美观?

java - 泛型类型 : Cannot specify sub-type when using . 类与泛型类型不兼容

java - Java 类型推断是如何工作的?