解决
我想创建一个泛型函数,它将返回枚举值的字典(也可以是泛型,例如int / byte / short)和显示名称属性。
到目前为止我所得到的是:
获取姓名和价值字典:
class EnumHelper ...
public static Dictionary<N, string> GetEnumDictionary<T, N>(bool displayName = false)
{
return Enum
.GetValues(typeof(T))
.Cast<T>()
.ToDictionary(t => (N)(object)t, t => t.ToString());
}
我用的是这样的:
var statuses = EnumHelper.GetEnumDictionary<LockStatus,int>();
并获取每个枚举值的显示名称属性:
public static class EnumExtensions
{
/// <summary>
/// A generic extension method that aids in reflecting
/// and retrieving any attribute that is applied to an `Enum`.
/// </summary>
public static TAttribute GetAttribute<TAttribute>(this Enum enumValue)
where TAttribute : Attribute
{
return enumValue.GetType()
.GetMember(enumValue.ToString())
.First()
.GetCustomAttribute<TAttribute>();
}
}
我用的是这样的:
var display = ((TicketEvent)n.Event).GetAttribute<DisplayAttribute>();
n.EventName = display.Name;
但我可以将它们结合起来。
有什么想法吗?
答案 0 :(得分:1)
查看我的ExtensionMethod
:
/// <summary>
/// includes all extensions for <see cref="Enum"/> operations.
/// </summary>
public static class EnumExtension
{
/// <summary>
/// Retreives the Description as string. If there is no Description. You will get null.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string GetDescription(this Enum obj)
{
object[] attribArray = obj.GetType().GetField(obj.ToString()).GetCustomAttributes(false);
if (attribArray.Length == 0)
return null;
if (attribArray[0] is DescriptionAttribute attrib)
{
return attrib.Description;
}
return null;
}
}
public enum MyEnum
{
[Description("It's Lorem")]
Lorem,
[Description("It's Ipsum")]
Ipsum
}
string description = MyEnum.Ipsum.GetDescription();
所以只需扩展我的方法。遍历所有字段并返回字符串。
答案 1 :(得分:0)
return Enum.GetValues(typeof(T))
.Cast<T>()
.ToDictionary(t => (N)(object)t, t => ((t as Enum).GetAttribute<DisplayAttribute>()).Name);