EnumHelper返回描述,而不是Enum值

我使用alertController.view.tintColor = Color.brandPurple 方法并尝试同时获取描述和EnumHelper值(Id),如下所示:

EnumHelper:

enum

枚举:

public static class MyEnumHelper
{
    public static string GetDescription<T>(this T enumerationValue)
        where T : struct
    {
        System.Type type = enumerationValue.GetType();
        if (!type.IsEnum)
        {
            throw new ArgumentException("Must be Enum type","enumerationValue");
        }
        //for the enum
        MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
        if (memberInfo != null && memberInfo.Length > 0)
        {
            object[] attrs = memberInfo[0]
                .getcustomAttributes(typeof(DescriptionAttribute),false);

            if (attrs != null && attrs.Length > 0)
            {
                return ((DescriptionAttribute)attrs[0]).Description;
            }
        }
        return enumerationValue.ToString();
    }
}


实体:

public enum StatusEnum
{
    [Description("Deleted")]
    Deleted= 0,[Description("active")]
    active= 1,[Description("Passive")]
    Passive= 2
}

控制器:

public class DemoEntity
{
    public int Id { get; set; }

    public StatusEnum StatusId { get; set; }

    [NotMapped]
    public string Statusname
    {
        get { return MyEnumHelper.GetDescription(StatusId); }
    }
}

但是,当尝试通过使用DemoEntity entity = DemoEntity(); entity.StatusId = StatusEnum.Passive; // !!! This returns "Passive" instead of its value 2. How can I get its value? 的强类型功能为Id分配enum的{​​{1}}值时,我仍然得到它的描述,而不是enum 。知道问题出在哪里吗?

angelbaiyun1983 回答:EnumHelper返回描述,而不是Enum值

如果需要该值,只需将枚举转换为int

entity.Id = (int)StatusEnum.Passive; 
,

我可能会这样做:

public enum Status
{
    Deleted= 0,Active= 1,Passive= 2
}

public class DemoEntity
{
    public int Id { get; set; }

    public Status Status { get; set; }

    [NotMapped]
    public string StatusName
    {
        get { return this.Status.ToString("g"); }
    }

    [NotMapped]
    public int StatusId
    {
        get { return (int)this.Status; }
    }
}
  • 不要在枚举后缀“ Enum”-对类(DemoEntityClass?)不这样做,并且Intellisense在类和枚举之间作了清楚的区分(例如)。 Microsoft不这样做(StringSplitOptions,而不是StringSplitOptionsEnum)
  • 如果您的描述属性与枚举名称值相同(如您所愿),则ToString(“ g”)是一个更简单的方法,可以将枚举名称转换为字符串
  • 枚举被命名为int;可以将int随意地映射到枚举。如果您尝试将一个int强制转换为一个枚举,但它不是该枚举的成员,则它只会以相同的int值进行操作(((Status)3).ToString()返回“ 3”);

如果您正忙于使用枚举,请考虑使用库Enums.Net

本文链接:https://www.f2er.com/3136099.html

大家都在问