Using string representations of enum values in switch-case

故事扮演 提交于 2019-11-30 11:37:09

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" ?

No, not necessarily: you are free to provide your own implementation of 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 enums instead.

Sanjeev

To add to the Peter Lawrey's comments, have a look at this post from last year which discusses Switching on String in Java before and after JDK7.

EDIT: Apologies for a C# answer to a Java question. 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.

As of C# 6, you can use this constant alternative: 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. Its value matches that of SomeEnum.ToString().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!