Numeric constants in enum (c#)

后端 未结 5 1338
既然无缘
既然无缘 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:32

    One way you could have numeric values associated with enums is by using the description attribute. For example you might have the enum:

    [Serializable]
    public enum SelectVersionEnum
    {
        [Description("2007")]
        v2007,
        [Description("2010")]
        v2010
    }
    

    You could then write an extension method to get the numeric value you are looking for.

    public static string Description(this Enum value)
    {
        var type = value.GetType();
    
        var name = Enum.GetName(type, value);
    
        if (name != null)
        {
            if (type.GetField(name) != null)
            {
                var attr = Attribute.GetCustomAttribute(type.GetField(name), typeof(DescriptionAttribute)) as DescriptionAttribute;
    
                return attr != null ? attr.Description : name;
            }
        }
    
        return null;
    
    } // end
    

    You would use it like this:

    var version = SelectVersionEnum.v2007.Description();
    

提交回复
热议问题