Choosing the default value of an Enum type without having to change values

前端 未结 13 2696
迷失自我
迷失自我 2020-12-04 07:46

In C#, is it possible to decorate an Enum type with an attribute or do something else to specify what the default value should be, without having the change the values? The

13条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 08:35

    If you define the Default enum as the enum with the smallest value you can use this:

    public enum MyEnum { His = -1, Hers = -2, Mine = -4, Theirs = -3 }
    
    var firstEnum = ((MyEnum[])Enum.GetValues(typeof(MyEnum)))[0];
    
    firstEnum == Mine.
    

    This doesn't assume that the enum has a zero value.

提交回复
热议问题