[英]Return enum list instead of string in enum extension helper
How can I convert the GetWithOrder
methods to return the actual enum in the correct order? 如何转换
GetWithOrder
方法以正确的顺序返回实际的枚举? It works for the string of the enum, but I want the actual Enum value, plus it needs to be generic of course. 它适用于枚举的字符串,但是我想要实际的Enum值,当然它也需要是通用的。
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class EnumOrderAttribute : Attribute
{
public int Order { get; set; }
}
public static class EnumExtenstions
{
public static IEnumerable<string> GetWithOrder(this Enum enumVal)
{
return enumVal.GetType().GetWithOrder();
}
public static IEnumerable<string> GetWithOrder(this Type type)
{
if (!type.IsEnum)
{
throw new ArgumentException("Type must be an enum");
}
// caching for result could be useful
return type.GetFields()
.Where(field => field.IsStatic)
.Select(field => new
{
field,
attribute = field.GetCustomAttribute<EnumOrderAttribute>()
})
.Select(fieldInfo => new
{
name = fieldInfo.field.Name,
order = fieldInfo.attribute != null ? fieldInfo.attribute.Order : 0
})
.OrderBy(field => field.order)
.Select(field => field.name);
}
}
public enum TestEnum
{
[EnumOrder(Order=2)]
Second = 1,
[EnumOrder(Order=1)]
First = 4,
[EnumOrder(Order=3)]
Third = 0
}
var names = typeof(TestEnum).GetWithOrder();
var names = TestEnum.First.GetWithOrder();
Extension method for the variable of enum type makes no sense because you don't need a value of that variable - you need only enum type. 枚举类型变量的扩展方法没有意义,因为您不需要该变量的值-您只需要枚举类型。 So I would go with static helper class:
因此,我将使用静态助手类:
public static class Enum<T>
{
public static IEnumerable<T> GetOrderedValues()
{
var type = typeof(T);
if (!type.IsEnum)
throw new InvalidOperationException();
return from f in type.GetFields(BindingFlags.Static | BindingFlags.Public)
orderby f.GetCustomAttribute<EnumOrderAttribute>()?.Order ?? Int32.MaxValue
select (T)f.GetValue(obj: null);
}
}
Note: enum type has a non-static value
field which actually holds the value of the enum. 注意:枚举类型具有一个非静态
value
字段,该字段实际上保存枚举的值。 So you need to take only static fields if you want to list enum members. 因此,如果要列出枚举成员,则只需采用静态字段。
Usage 用法
var values = Enum<Fruits>.GetOrderedValues();
For sample enum 对于示例枚举
public enum Fruits
{
Banana,
[EnumOrder(2)]
Apple,
[EnumOrder(1)]
Lemon
}
Output will be 输出将是
[ Lemon, Apple, Banana ]
Members without EnumOrder
attribute will go last, but you can change that behavior if you'll use some other default order instead of Int32.MaxValue
. 没有
EnumOrder
属性的成员将排在最后,但是如果您使用其他默认顺序代替Int32.MaxValue
,则可以更改该行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.