How to assign string values to enums and use that value in a switch

后端 未结 10 1646
小鲜肉
小鲜肉 2021-02-02 10:45

Basically a series of titles will be passed into the switch statement and I need to compare them against the string values of the enum. But I have little to no idea how to do th

10条回答
  •  北海茫月
    2021-02-02 11:22

    I wanted to add another answer for anyone using C# 6 or greater.

    If you are only wanting to get the name of the Enum value, you could use the new nameof() method introduced in C# 6.

    string enumName = nameof(MyEnum.EnumVal1); // enumName will equal "EnumVal1"
    

    While this may seem like overkill at first glance (why not just set the value of the string to "EnumVal1" to start with?), it will give you compile-time checking to make sure the value is valid. So, if you ever change the name of the enum value and forget to tell your IDE to find and replace all references, it will not compile until you fix them.

提交回复
热议问题