![](/img/trans.png)
[英]What's the easiest way to convert a list of integers to a string of comma separated numbers in C#
[英]What's the easiest way to convert from a bool to string in C#?
我很想使用if ... else ...
但我想知道是否有更簡單的方法? 我需要在消息框中顯示true或false結果。
bool.ToString
方法已經做了你想要的。
此方法返回常量“True”或“False”。
但實際上,您通常不需要直接從代碼中顯式調用ToString
。 如果您已經在編寫字符串,那么最簡單的方法是使用連接:
string message = "The result is " + b;
這將編譯為對string.Concat
的調用,並為您調用ToString
方法。
在某些情況下,使用String.Format
會很有用,並且再次為您調用ToString
方法:
string message = string.Format("The result is {0}. Try again?", b);
bool b = true;
Console.WriteLine(b.ToString());
我要扔掉:
val ? "true" : "false"
混合,因為通常需要小寫結果(許多機器可讀的格式,例如許多XML格式,對於布爾值使用小寫“true”和“false”)並且上面的更快也是IMO比val.ToString().ToLowerInvariant()
更清潔val.ToString().ToLowerInvariant()
。
當然,延伸到val ? "yes" : "no"
val ? "yes" : "no"
等等是微不足道的。 可定位是另一回事,並不總是微不足道(如果翻譯得好,很多情況會有完全不同的句子,所以messageStart + (val ? "yes" : "no") + messageEnd
的邏輯messageStart + (val ? "yes" : "no") + messageEnd
並不總能正常工作。
bool v = true;
string s = v.ToString();
.ToString()
有什么問題,它可以在每個對象上使用?
bool myBool = false;
string myString = myBool.ToString();
這是一個單行。 所有c#類型都派生自Object
,因此繼承該類的方法。
我會在這里指出你: http : //msdn.microsoft.com/en-us/library/system.object.aspx並讓你找到它。
bool myBool = true;
MessageBox.show(myBool.toString());
始終建議在Convert類下使用靜態函數。 在你的情況下
bool boolValue = true; System.Convert.ToString(boolValue);
如果要使其完全可本地化,可以將名為UiStrings的資源文件添加到項目中,並為每個布爾值添加一個條目。 Visual Studio將為資源管理器生成一個包裝器(使用PublicResXFileCodeGenerator或ResXFileCodeGenerator),然后您可以使用靜態屬性訪問該包裝器。
然后,您可以像這樣使用它:
var booleanValue = true;
var booleanText = booleanValue ? UiStrings.TrueValueText : UiStrings.FalseValueText;
var messageText = UiString.ResultMessageText;
var messageString = String.Format("{0}:{1}", messageText, booleanText);
詳細的代碼是有意的,以便您可以識別不同的部分。
我知道你沒有問這個問題,但是為了把我自己的自戀語音添加到混音中,這就是你如何從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
}
}
輸出:
1
0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.