在 switch-case 中使用枚举值的字符串表示
为什么不能在 switch case 中使用枚举值作为字符串?(或者这有什么问题:)
Why is it not possible to use enum values as strings in a switch case? (Or what is wrong with this:)
String argument;
switch (argument) {
case MyEnum.VALUE1.toString(): // Isn't this equal to "VALUE1" ?
// something
break;
case MyEnum.VALUE2.toString():
// something else
break;
推荐答案
只能使用编译时已知的字符串.编译器无法确定该表达式的结果.
You can only use strings which are known at compile time. The compiler cannot determine the result of that expression.
也许你可以试试
String argument = ...
switch(MyEnum.valueOf(argument)) {
case VALUE1:
case VALUE2:
相关文章