Get int value from enum in C#

前端 未结 28 1932
臣服心动
臣服心动 2020-11-22 04:58

I have a class called Questions (plural). In this class there is an enum called Question (singular) which looks like this.

public e         


        
28条回答
  •  [愿得一人]
    2020-11-22 05:42

    Since enums can be declared with multiple primitive types, a generic extension method to cast any enum type can be useful.

    enum Box
    {
        HEIGHT,
        WIDTH,
        DEPTH
    }
    
    public static void UseEnum()
    {
        int height = Box.HEIGHT.GetEnumValue();
        int width = Box.WIDTH.GetEnumValue();
        int depth = Box.DEPTH.GetEnumValue();
    }
    
    public static T GetEnumValue(this object e) => (T)e;
    

提交回复
热议问题