c# - 为什么 bool.TrueString 和 bool.FalseString 存在?

标签 c# boolean string-literals

我正在阅读 boolean structure 的 MSDN 文章,当我看到一个 boolean 值有两个字段时:TrueStringFalseString .它们分别返回“True”和“False”。

经过一些搜索,我能找到的唯一例子是 this dotnetperls article .文章指出:

Programs often need these strings. TrueString and FalseString are a useful pair of readonly members. They represent truth values in string format. They provide indirection and abstraction over directly using string literals.

所以看起来它在某些情况下很有用。但同一篇文章未能提供一个真实的例子(恕我直言)。

一些进一步的阅读也引起了我的注意:TrueString 和 FalseString 是公共(public)静态只读字段。和 this dornetperls article状态:

The language specification recommends using public static readonly fields ... when the field is subject to change in the future.

现在这个我有点明白了。如果 .NET 开发人员决定将“True”和“False”分别更改为“OkeyDokey”和“Negatory”,那么使用 TrueString 和/或 FalseString 是明智的做法。

但这仍然留给我一个问题:在什么样的场景下你想比较一个字符串和一个 boolean 值的字符串字面量?因为表面上看:“程序经常需要”它们。

最佳答案

string.Empty 存在的原因相同。有些人更喜欢在代码中使用语义命名的值而不是文字值。

在现代 .NET(.NET Framework 之后的任何版本)中,以下代码打印 True 三次:

Console.WriteLine(ReferenceEquals("True", bool.TrueString));
Console.WriteLine(ReferenceEquals("False", bool.FalseString));
Console.WriteLine(ReferenceEquals("", string.Empty));

这告诉我们文字和字段之间零运行时差异。它们在运行时是完全相同的对象。

sharplab.io here 上亲自尝试一下.


其他人提到在解析 boolean 字符串时使用它来比较,但我不建议这样做。如果要将 string 转换为 bool,请使用 bool.TryParsebool.Parse。使用 == 进行区分大小写的比较,这可能不是您想要的。此外,该框架的方法专门针对常见情况进行了优化。您可以在 GitHub 上的代码中看到这些优化:https://github.com/dotnet/runtime/blob/f8fa9f6d1554e8db291187dd7b2847162703381e/src/libraries/System.Private.CoreLib/src/System/Boolean.cs#L226

关于c# - 为什么 bool.TrueString 和 bool.FalseString 存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17447463/

相关文章:

c# - 如何使用 Linq 在列表中查找两个连续项目的子列表

c# - 反转对象或用减号将其标记为负数

c - C 中 char *str ="this is a string"与 char *str = strdup ("this is a string"之间的区别是什么

c++ - (c/c++) 字符串文字的拷贝是否在 TEXT 部分共享内存?

JAVA:创建 boolean 变量或在 If 语句中放置参数?

java - 检查 2 个不同的相等实例(包含示例)

c# - 读取麦克风分贝和音调/频率

c# - TCP 数据包丢失

java - while 循环的问题

java - 在新方法中使用 boolean 结果时出错 - 需要字符串,但找到 boolean 值