简体   繁体   English

在C#中从bool转换为字符串的最简单方法是什么?

[英]What's the easiest way to convert from a bool to string in C#?

I am tempted to use an if ... else ... but I am wondering if there's an easier way? 我很想使用if ... else ...但我想知道是否有更简单的方法? I need to display the true or false result in a message box. 我需要在消息框中显示true或false结果。

The bool.ToString method already does what you want. bool.ToString方法已经做了你想要的。

This method returns the constants "True" or "False". 此方法返回常量“True”或“False”。

However in practice it is not that often that you need to explicitly call ToString directly from your code. 但实际上,您通常不需要直接从代码中显式调用ToString If you are already writing a string then the easiest way is to use concatenation: 如果您已经在编写字符串,那么最简单的方法是使用连接:

string message = "The result is " + b;

This compiles to a call to string.Concat and this calls the ToString method for you. 这将编译为对string.Concat的调用,并为您调用ToString方法。

In some situations it can be useful to use String.Format , and again the ToString method is called for you: 在某些情况下,使用String.Format会很有用,并且再次为您调用ToString方法:

string message = string.Format("The result is {0}. Try again?", b);
bool b = true;
Console.WriteLine(b.ToString());

I'm just going to throw: 我要扔掉:

val ? "true" : "false"

into the mix, as having a lowercase result is often necessary (a lot of machine-readable formats, such as a lot of XML formats, use lower case "true" and "false" for boolean values) and the above is faster and also IMO cleaner than val.ToString().ToLowerInvariant() . 混合,因为通常需要小写结果(许多机器可读的格式,例如许多XML格式,对于布尔值使用小写“true”和“false”)并且上面的更快也是IMO比val.ToString().ToLowerInvariant()更清洁val.ToString().ToLowerInvariant()

Of course, extension to val ? "yes" : "no" 当然,延伸到val ? "yes" : "no" val ? "yes" : "no" and so on is trivial. val ? "yes" : "no"等等是微不足道的。 To be localisable is another matter, and not always trivial (quite a few cases would have quite different sentences if translated well, so the logic of messageStart + (val ? "yes" : "no") + messageEnd doesn't always work well. 可定位是另一回事,并不总是微不足道(如果翻译得好,很多情况会有完全不同的句子,所以messageStart + (val ? "yes" : "no") + messageEnd的逻辑messageStart + (val ? "yes" : "no") + messageEnd并不总能正常工作。

bool v = true;  
string s = v.ToString();

What is wrong with .ToString() , which is available on every object? .ToString()有什么问题,它可以在每个对象上使用?

bool myBool = false;
string myString = myBool.ToString();

This is a one-liner. 这是一个单行。 All c# types derive from Object and so inherit the methods of that class. 所有c#类型都派生自Object ,因此继承该类的方法。

I'll point you here: http://msdn.microsoft.com/en-us/library/system.object.aspx and let you find it. 我会在这里指出你: http//msdn.microsoft.com/en-us/library/system.object.aspx并让你找到它。

  bool myBool = true;  
  MessageBox.show(myBool.toString());

It is always recommended to use static functions under Convert class. 始终建议在Convert类下使用静态函数。 In your case 在你的情况下

bool boolValue = true; bool boolValue = true; System.Convert.ToString(boolValue); System.Convert.ToString(boolValue);

If you want to make it fully localizable, you can add a resource file called UiStrings to the project and add an entry for each of the boolean values. 如果要使其完全可本地化,可以将名为UiStrings的资源文件添加到项目中,并为每个布尔值添加一个条目。 Visual Studio will generate a wrapper (using either PublicResXFileCodeGenerator or ResXFileCodeGenerator) for the resource manager, which you can then access using static properties. Visual Studio将为资源管理器生成一个包装器(使用PublicResXFileCodeGenerator或ResXFileCodeGenerator),然后您可以使用静态属性访问该包装器。

Then, you can use it like this: 然后,您可以像这样使用它:

var booleanValue = true;  
var booleanText = booleanValue ? UiStrings.TrueValueText : UiStrings.FalseValueText;  
var messageText = UiString.ResultMessageText;  
var messageString = String.Format("{0}:{1}", messageText, booleanText);

The verbose code is intentional so that you can identify the different parts. 详细的代码是有意的,以便您可以识别不同的部分。

I know you didn't ask this, but for the heck of adding my own narcissistic voice to the mix, this is how to you get an int from a bool (0, 1) 我知道你没有问这个问题,但是为了把我自己的自恋语音添加到混音中,这就是你如何从bool(0,1)获得一个int

using System;

class Program
{
    static void Main()
    {
        // Example bool is true
        bool t = true;

        // A
        // Convert bool to int
        int i = t ? 1 : 0;
        Console.WriteLine(i); // 1

        // Example bool is false
        bool f = false;

        // B
        // Convert bool to int
        int y = Convert.ToInt32(f);
        Console.WriteLine(y); // 0
    }
}

Output: 输出:

1 1

0 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM