这段代码应该在任何枚举上提供一个通用的扩展方法,让您检索通用属性。它使用起来更简单,而且稍微——你只需要传入泛型类型。
public static string GetDescription(this Enum value)
{
var type = value.GetType();
var name = Enum.GetName(type, value);
if (string.IsNullOrWhiteSpace(name))
return value.ToString();
var field = type.GetField(name);
var des = field?.GetCustomAttribute<DescriptionAttribute>();
if (des == null)
return value.ToString();
return des.Description;
}以下是调用示例代码
public enum MyEnum
{
[Description("Here is Name")]
Name1 = 1,
[Description("Here Is Another")]
HereIsAnother = 2,
[Description("Last one")]
LastOne = 3
}var strDescription = MyEnum.HereIsAnother.GetDescription();版权声明:本文为liaohaiyin原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。