为什么 Boolean.ToString 输出“True"?而不是“真实的" [英] Why does Boolean.ToString output "True" and not "true"

查看:19
本文介绍了为什么 Boolean.ToString 输出“True"?而不是“真实的"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

true.ToString() 
false.toString();

Output:
True
False

它是真"而不是真"有正当理由吗?它在将 XML 编写为 XML 的布尔类型 小写 时会中断,并且与 C# 的 true/false 不兼容(虽然不确定 CLS).

Is there a valid reason for it being "True" and not "true"? It breaks when writing XML as XML's boolean type is lower case, and also isn't compatible with C#'s true/false (not sure about CLS though).

更新

这是我在 C# 中绕过它的非常老套的方法(用于 XML)

Here is my very hacky way of getting around it in C# (for use with XML)

internal static string ToXmlString(this bool b)
{
    return b.ToString().ToLower();
}

当然,这会在堆栈中增加 1 个方法,但会在任何地方删除 ToLowers().

Of course that adds 1 more method to the stack, but removes ToLowers() everywhere.

推荐答案

只有微软的人才可以真正回答这个问题.不过,我想提供一些有趣的事实;)

Only people from Microsoft can really answer that question. However, I'd like to offer some fun facts about it ;)

首先,这是 MSDN 中关于 Boolean.ToString() 方法的说法:

First, this is what it says in MSDN about the Boolean.ToString() method:

返回值

类型:System.String

Type: System.String

TrueString 如果这个值实例为真,或 FalseString 如果此实例的值为 false.

TrueString if the value of this instance is true, or FalseString if the value of this instance is false.

备注

此方法返回常量真"或假".注意XML 区分大小写,并且XML 规范承认真"和假"作为有效的集合布尔值.如果字符串对象ToString() 方法返回将被写入一个 XML 文件,它的String.ToLower 方法应该是首先调用将其转换为小写.

This method returns the constants "True" or "False". Note that XML is case-sensitive, and that the XML specification recognizes "true" and "false" as the valid set of Boolean values. If the String object returned by the ToString() method is to be written to an XML file, its String.ToLower method should be called first to convert it to lowercase.

有趣的事实#1 出现了:它根本不返回 TrueString 或 FalseString.它使用硬编码的文字True"和False".如果它使用这些字段对你没有任何好处,因为它们被标记为只读,所以没有改变它们.

Here comes the fun fact #1: it doesn't return TrueString or FalseString at all. It uses hardcoded literals "True" and "False". Wouldn't do you any good if it used the fields, because they're marked as readonly, so there's no changing them.

另一种方法,Boolean.ToString(IFormatProvider) 更有趣:

The alternative method, Boolean.ToString(IFormatProvider) is even funnier:

备注

提供者参数是保留的.它不参与此方法的执行.这意味着 Boolean.ToString(IFormatProvider) 方法与大多数具有提供程序参数的方法不同,它不反映特定于区域性的设置.

The provider parameter is reserved. It does not participate in the execution of this method. This means that the Boolean.ToString(IFormatProvider) method, unlike most methods with a provider parameter, does not reflect culture-specific settings.

解决办法是什么?取决于你到底想做什么.不管是什么,我打赌它都需要破解 ;)

What's the solution? Depends on what exactly you're trying to do. Whatever it is, I bet it will require a hack ;)

这篇关于为什么 Boolean.ToString 输出“True"?而不是“真实的"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆