[英]How to convert string to bool
private void okButton_Click (object sender, EventArgs e) {
string city; //holds the city name
if (cityListBox.SelectedIndex != -1) {
//Get the selected item
city = cityListBox.SelectedItem.ToString ();
//determine the time zone
if (city) {
if (city == "Honolulu")
timeZoneLabel.Text = "Hawaii-Aleutian";
else if (city == "San Francisco")
timeZoneLabel.Text = "pacific";
else if (city == "Denver")
timeZoneLabel.Text = "Mountain";
else if (city == "Minneapolis")
timeZoneLabel.Text = "Central";
else if (city == "New York")
timeZoneLabel.Text = "Eastern";
}
} else
//No city was selected
MessageBox.Show ("Select a city");
}
在“ //確定時區”正下方,括號中的“城市”不斷出現錯誤,提示它無法將字符串轉換為布爾值。 我想念什么?
除非不需要檢查是否為空或為空,否則不需要外部if-stmt,在這種情況下,將執行以下操作:
if (!string.IsNullOrEmpty(city)) {
if (city == "Honolulu")
timeZoneLabel.Text = "Hawaii-Aleutian";
else if (city == "San Francisco")
timeZoneLabel.Text = "pacific";
else if (city == "Denver")
timeZoneLabel.Text = "Mountain";
else if (city == "Minneapolis")
timeZoneLabel.Text = "Central";
else if (city == "New York")
timeZoneLabel.Text = "Eastern";
}
要使用if語句,您必須輸入一個對或錯(布爾)的方程式。
如果為“ true”,則執行if-block命令。
如果為“ false”,則跳過if塊。
一些例子:
(“ Hello” .Equals(“ Test”))-> False
(1 +1 == 2)->正確
(5 <6)->正確
(錯誤)->錯誤
在if語句中輸入字符串會返回錯誤,因為您沒有輸入true或false語句。 該程序不知道該字符串如何處理。
我認為您可能會將if語句與switch語句混淆。
閱讀這些MSDN文檔以獲取更多信息:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.