我更喜欢使用枚举而不是“魔术字符串”。它们是类型安全的并且不易出错。您也可以将字符串转换为枚举,这很适合您的问题:
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;
}
}