[英]Using string representations of enum values in 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.
编译器无法确定该表达式的结果。
Perhaps you can try 也许你可以试试
String argument = ...
switch(MyEnum.valueOf(argument)) {
case VALUE1:
case VALUE2:
case MyEnum.VALUE1.toString(): // Isn't this equal to "VALUE1" ?
case MyEnum.VALUE1.toString()://这不等于“VALUE1”吗?
No, not necessarily: you are free to provide your own implementation of toString()
不,不一定:您可以自由提供自己的
toString()
public enum MyType {
VALUE1 {
public String toString() {
return "this is my value one";
}
},
VALUE2 {
public String toString() {
return "this is my value two";
}
}
} }
Moreover, someone who is maintaining your code could add this implementation after you leave the company. 此外,维护代码的人可以在您离开公司后添加此实现。 That is why you should not rely on String values, and stick to using numeric values (as represented by the constants
MyEnum.VALUE1
, MyEnum.VALUE2
, etc.) of your enum
s instead. 这就是为什么你不应该依赖String值,而是坚持使用你的
enum
的数值(由常量MyEnum.VALUE1
, MyEnum.VALUE2
等表示)。
EDIT : Apologies for a C# answer to a Java question. 编辑 :为Java问题的C#答案道歉。 I don't know what went wrong there.
我不知道那里出了什么问题。
It is possible to use string values (including the string values of enums). 它可以使用字符串值(包括枚举的字符串值)。 However, you may only use compile-time constants .
但是,您可能只使用编译时常量 。 You are calling a method,
ToString()
, which needs to be evaluated at runtime. 您正在调用一个方法
ToString()
,该方法需要在运行时进行评估。
As of C# 6, you can use this constant alternative: case nameof(SomeEnum.SomeValue):
从C#6开始,您可以使用此常量替代方法:
case nameof(SomeEnum.SomeValue):
Nameof() is evaluated at compile time, simply to a string that matches the (unqualified) name of the given variable, type, or member. Nameof()在编译时被评估,只是与给定变量,类型或成员的(非限定)名称匹配的字符串。 Its value matches that of
SomeEnum.ToString()
. 它的值与
SomeEnum.ToString()
值相匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.