- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在阅读 boolean structure 的 MSDN 文章,当我看到一个 boolean 值有两个字段时:TrueString和 FalseString .它们分别返回“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.TryParse
或 bool.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/
我正在阅读 boolean structure 的 MSDN 文章,当我看到一个 boolean 值有两个字段时:TrueString和 FalseString .它们分别返回“True”和“Fals
我是一名优秀的程序员,十分优秀!