Initialize enum with a null value

北慕城南 提交于 2019-12-08 15:42:39

问题


How do i create an enum with a null value

ex:

public enum MyEnum
{
    [StringValue("X")]
    MyX,
    [StringValue("Y")]
    MyY,      
    None
}

where None value is null or String.Empty


回答1:


You can try something like this:-

public MyEnum? value= null;

or you can try this:-

 public MyEnum value= MyEnum.None;



回答2:


As all the other answers said, you can't have an enum value be null. What you can do is add a Description attribute (like your StringValue) which has a null value.

For instance:

public enum MyEnum
{
    [Description(null)]
    None = 0,
    [Description("X")]
    MyX,
    [Description("Y")]
    MyY
}

You can get the description of the Enum with the following function:

    public static string GetEnumDescription(Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fi.GetCustomAttributes(
            typeof(DescriptionAttribute),
            false);

        if (attributes != null && attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }

Usage:

MyEnum e = MyEnum.None;
string s2 = GetEnumDescription((MyEnum)e); // This returns null



回答3:


use the "?" oeprator for a nullable type !!

public MyEnum? myEnum= null;



回答4:


All enum types are value types and the different members are also derived from member types (the allowed types are byte, sbyte, short, ushort, int, uint, long, or ulong - as documented).

This means that members of an enumeration cannot be null.

One way to deal with a default enum value is to put the None value as the first value and setting it to a negative value (for signed enums) or 0.

public enum MyEnum
{
    [StringValue(null)]
    None = -1,
    [StringValue("X")]
    MyX,
    [StringValue("Y")]
    MyY      
}

You can have a null reference to an enumeration if you declare a nullable instance - myenum?.




回答5:


There is no such thing as an "enum with a null value". An enum in C# is just a named integer. In your case, None is just an alias for 2 (for completeness, MyX is 0 and MyY is 1). By default, the underlying data-type of an enum is int, but it can also be other integer-based primitive types of different sizes/sign.

If you want a "null" enum, you would have to use MyEnum?, aka Nullable<MyEnum>.



来源:https://stackoverflow.com/questions/13605303/initialize-enum-with-a-null-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!