【发布时间】:2019-11-08 17:28:56
【问题描述】:
我使用EnumHelper 方法并尝试获取描述和enum 值(Id),如下所示:
枚举助手:
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?
但是,当尝试使用如上所示的enum 的强类型功能为enum 分配Id 值时,我仍然得到它的描述而不是Id。知道问题出在哪里吗?
【问题讨论】:
-
我认为这是描述的重点,以字符串格式显示值。号码还在后面。如果你真的想看这个数字,你可以把它转换成一个整数。
-
(int)StatusEnum.Passive应该会为您提供整数值。 -
@JohnPete。投票赞成。在这种情况下,Entity 和 Enum 定义中的这种方法没有问题,我只需在需要枚举值时将其转换为 int 值。真的吗?或者您有没有比这更好的建议?
-
@the_lotus。在这种情况下,Entity 和 Enum 定义中的这种方法没有问题,我只需在需要枚举值时将其转换为 int 值。真的吗?或者您有没有比这更好的建议?
-
我个人认为没有必要;提供东西意味着人们倾向于使用它们,并且当使用 int 而不是 enum 时会导致质量较差的代码。例如,这行代码是什么意思:
if(activity.Phase == 2 || (activity.Phase == 3 && (activity.ProtectionModes & 1 == 1)))?是的..除非你知道这些数字是什么,否则它没有任何意义。比较if(activity.Phase == Phase.Starting || (activity.Phase == Phase.Running && (activity.ProtectionModes & Modes.CanAutoShutdown == Modes.CanAutoShutDown)))- 您可以立即知道此if运行的条件
标签: c# asp.net asp.net-mvc asp.net-core enums