gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:16:13 32 4
gpt4 key购买 nike

我正在阅读 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/

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