我们Description
在 dot net CLI 中有枚举属性吗?(Dot Net Core RC2)如果没有,还有其他选择吗?
问问题
23633 次
6 回答
15
对于 1.0 和 1.1,DescriptionAttribute
现在在System.ComponentModel.Primitives
NuGet 包中。
于 2017-04-18T23:51:11.253 回答
12
我不得不修改@yaniv 的答案以使用该DescriptionAttribute
类型并获取该Description
字段。
public static class EnumExtensions
{
/// <summary>
/// Get the Description from the DescriptionAttribute.
/// </summary>
/// <param name="enumValue"></param>
/// <returns></returns>
public static string GetDescription(this Enum enumValue)
{
return enumValue.GetType()
.GetMember(enumValue.ToString())
.First()
.GetCustomAttribute<DescriptionAttribute>()?
.Description ?? string.Empty;
}
}
于 2019-03-25T13:09:52.283 回答
11
我将它用于我的 Net Framework 实现:
public static class EnumerationExtension
{
public static string Description( this Enum value )
{
// get attributes
var field = value.GetType().GetField( value.ToString() );
var attributes = field.GetCustomAttributes( typeof( DescriptionAttribute ), false );
// return description
return attributes.Any() ? ( (DescriptionAttribute)attributes.ElementAt( 0 ) ).Description : "Description Not Found";
}
}
这不适用于 NetCore,因此我对其进行了修改以执行此操作:
public static class EnumerationExtension
{
public static string Description( this Enum value )
{
// get attributes
var field = value.GetType().GetField( value.ToString() );
var attributes = field.GetCustomAttributes( false );
// Description is in a hidden Attribute class called DisplayAttribute
// Not to be confused with DisplayNameAttribute
dynamic displayAttribute = null;
if (attributes.Any())
{
displayAttribute = attributes.ElementAt( 0 );
}
// return description
return displayAttribute?.Description ?? "Description Not Found";
}
}
枚举示例:
public enum ExportTypes
{
[Display( Name = "csv", Description = "text/csv" )]
CSV = 0
}
任一静态添加的示例用法:
var myDescription = myEnum.Description();
于 2017-01-05T16:27:55.123 回答
3
DescriptionAttribute
被添加到 CoreFX,但仅在 RC2 之后。所以它会出现在 RTM 版本中,但不会出现在 RC2 中。根据您想要做什么,创建自己的属性可能会起作用。
于 2016-05-22T14:24:55.603 回答
2
您可以使用“DisplayAttribute”并执行
public static string Description(this Enum enumValue)
{
return enumValue.GetType()
.GetMember(enumValue.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()
.GetDescription();
}
于 2018-10-02T09:51:09.393 回答
1
为了避免按照@pamcevoj 的回答使用 System.Reflection 并按照@HouseCat 的回答使用动态,我在基于@HouseCat 解决方案的.NET Core 3.1 中找到了这个解决方案
public static string Description(this Enum enumValue)
{
var descriptionAttribute = enumValue.GetType()
.GetField(enumValue.ToString())
.GetCustomAttributes(false)
.SingleOrDefault(attr => attr.GetType() == typeof(DescriptionAttribute)) as DescriptionAttribute;
// return description
return descriptionAttribute?.Description ?? "";
}
于 2021-01-20T10:43:10.407 回答