Methods inside enum in C#

后端 未结 6 1325
离开以前
离开以前 2020-12-04 10:21

In Java, it\'s possible to have methods inside an enum.

Is there such possibility in C# or is it just a string collection and that\'s it?

I tried to override

6条回答
  •  一整个雨季
    2020-12-04 11:08

    Since I came across, and needed the exact opposite of enum to string, here is a Generic solution:

    static class EnumExtensions {
        public static T GetEnum(this string itemName) {
            return (T) Enum.Parse(typeof(T), itemName, true);
        }
    }
    

    This also ignores case and is very handy for parsing REST-Response to your enum to obtain more type safety. Hopefully it helps someone

提交回复
热议问题