我寧願使用枚舉而不是「magic strings」。它們是類型安全的,並且錯誤較少。您可以將字符串轉換爲一個枚舉,以及它本身很適合你的問題:
public enum DifficultyEnum {
NULL,
Easy,
Medium,
Hard
}
public DifficultyEnum GetDifficulty() {
var difficulty = DifficultyEnum.NULL;
var selItem = listBox1.SelectedItem.ToString();
Enum.TryParse<DifficultyEnum>(selItem, out difficulty);
return difficulty;
}
然後在您的其他類:
swtich (classInstance.GetDifficulty()) {
case Easy:
break;
case Medium:
break;
case Hard:
break;
case NULL: /*Hopefully you don't get here but be defensive and expect that somehow they'll manage to do so =P */
break;
}
編輯:
這是一個問題的偏好,但你也可以使GetDifficulty()
成爲一個屬性,而不是像這樣:
public DifficultyEnum Difficulty {
get {
var difficulty = DifficultyEnum.NULL;
var selItem = listBox1.SelectedItem.ToString();
Enum.TryParse<DifficultyEnum>(selItem, out difficulty);
return difficulty;
}
}
看起來比較小巧。而是返回一個字符串,我建議返回一個枚舉。此外,您可以將信息類傳遞給沒有它的類,然後從屬性中訪問信息。 – Trisped