我使用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
。知道问题出在哪里吗?
答案 0 :(得分:2)
如果需要该值,只需将枚举转换为int
entity.Id = (int)StatusEnum.Passive;
答案 1 :(得分:1)
我可能会这样做:
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; }
}
}
((Status)3).ToString()
返回“ 3”); 如果您正忙于使用枚举,请考虑使用库Enums.Net