Get int value from enum in C#

前端 未结 28 2281
臣服心动
臣服心动 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:30

    Since Enums can be any integral type (byte, int, short, etc.), a more robust way to get the underlying integral value of the enum would be to make use of the GetTypeCode method in conjunction with the Convert class:

    enum Sides {
        Left, Right, Top, Bottom
    }
    Sides side = Sides.Bottom;
    
    object val = Convert.ChangeType(side, side.GetTypeCode());
    Console.WriteLine(val);
    

    This should work regardless of the underlying integral type.

提交回复
热议问题