儘管其他答案顯示了這樣做的方法。我會建議他們,我會使用正確的工具。
你想要什麼,從概念上講,是字典是翻譯的等級(整數),爲一個字符串,所以我會走那個路線:
// We are going to use integer keys, with string values
var stringGrades = new Dictionary<int, string>()
{
{1, "good"}, // 1 is the Key, "good" is the Value
{2, "decent"},
{3, "bad"}
};
int integerGrade;
string textGrade;
// try to convert the textbox text to an integer
if(!Int32.TryParse(txtb_note.Text, out integerGrade)
// if successful, try to find the resulting integer
// (now in "integerGrade") among the keys of the dictionary
|| !stringGrades.TryGetValue(integerGrade, out textGrade))
// Any of the above conditions weren't successful, so it's invalid
lbl_ergebnis.Text = "Invalid value";
else
// It worked, so now we have our string value in the variable "textGrade"
// obtained by the "out textGrade" parameter on TryGetValue
lbl_ergebnis.Text = textGrade;
在特定情況下,你是利用原有等級從一個文本字符串,所以走這條路,如果你喜歡:
// This time, we directly use string as keys
var stringGrades = new Dictionary<string, string>()
{
{"1", "good"},
{"2", "decent"},
{"3", "bad"}
};
string textGrade;
// Try to get the value in the dictionary for the key matching the text
// on your textbox, no need to convert to integer
if(!stringGrades.TryGetValue(txtb_note.Text, out textGrade))
lbl_ergebnis.Text = "Invalid value";
else
lbl_ergebnis.Text = textGrade;
由於TryGetValue
和out
參數可能會產生混淆,這裏是另一種方式來做到這一點,這可能是更容易閱讀,如果你是新的節目(我們將使用同樣的<string, string>
字典如上):
// If our dictionary doesn't contain the key we are looking for,
// the input is invalid
if(!stringGrades.ContainsKey(txtb_note.Text))
lbl_ergebnis.Text = "Invalid value";
else
// it contains the key, so let's show its value:
lbl_ergebnis.Text = stringGrades[txtb_note.Text];
其中,如果你想循環的循環,可以轉換爲一個單一的代碼行,如:
lbl_ergebnis.Text = stringGrades.ContainsKey(txtb_note.Text) ?
stringGrades[txtb_note.Text] : "Invalid value";
(不通過這最後的代碼混淆,正如我所說,這只是「循環迴路」)
的其他方式(使用switch
或if-else
)工作,但不是正確的OOL。從概念上思考,你想要做的是將一個值轉換爲不同的值:這是一個字典,並且在.NET中有相應的工具(Dictionary<T,T2>
類)
如果你將來需要其他等級,你可以將它們添加到字典中,並且轉換字符串的代碼將繼續工作。另外,該字典不需要存儲在代碼中:它可以從文本文件,Web服務,數據庫或其他任何東西中檢索,然後它甚至可以在沒有重新編譯應用程序的情況下工作。
如果你想處理*數字*,但此刻你有*字符串*,第一步應該是解析字符串。 'Int32.TryParse'可能是一個很好的開始... – 2015-02-05 18:44:25
btw:你可以看一下枚舉器 – jean 2015-02-05 18:44:47
又一個變種:use [switch](https://msdn.microsoft.com/en-us/library/06tc147t .aspx)like switch(txtb_note.Text){case「1」:... break; case「2」:... break; ...; '' – Grundy 2015-02-05 18:49:03