Numeric constants in enum (c#)

后端 未结 5 1339
既然无缘
既然无缘 2021-01-24 05:06

I\'m creating this selectbox in a SharePoint web part and need to have a drop down with the current version so I need to use an Enum.

public enum SelectVersionEn         


        
5条回答
  •  清歌不尽
    2021-01-24 05:31

    No, you can not name enums with integer names.

    An enum value name is a normal identifier and must follow the same rules as everything else.

    You can, however, use:

    public enum SelectVersionEnum
    {
        Version2007 = 12,
        Version2010 = 14
    }
    

    Additionally, Enum.Parse can parse strings with integers into their corresponding enum value, even if value described in the string doesn't exist.

    Try the following in LINQPad:

    void Main()
    {
        Enum.Parse(typeof(SelectVersionEnum), "12").Dump();
        Enum.Parse(typeof(SelectVersionEnum), "14").Dump();
        Enum.Parse(typeof(SelectVersionEnum), "2007").Dump();
    }
    
    public enum SelectVersionEnum
    {
        Version2007 = 12,
        Version2010 = 14
    }
    

    The output:

    Version2007
    Version2010
    2007

    What do you think would've happened if you defined the following:

    public enum SelectVersionEnum
    {
        12 = 14,
        14 = 16
    }
    

    Does the string "14" now mean "12" or "14"?

提交回复
热议问题