在声明顺序中排序枚举 [英] Sort enums in declaration order

查看:130
本文介绍了在声明顺序中排序枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public enum CurrencyId
{
    USD = 840,
    UAH = 980,
    RUR = 643,
    EUR = 978,
    KZT = 398,
    UNSUPPORTED = 0
}

有没有办法排序 Enum.GetValues(typeof(CurrencyId))的结果。Cast< CurrencyId>()按照它们在.cs文件中声明(USD, UAH,RUR,EUR,KZT,UNSUPPORTED),而不是其底层代码?个人而言,我认为答案是不,因为原始的命令在二进制文件中丢失,所以...如何执行任务?

Is there any way to sort results of Enum.GetValues(typeof(CurrencyId)).Cast<CurrencyId>() by order they are declared in .cs file (USD, UAH, RUR, EUR, KZT, UNSUPPORTED), not by their underlying code? Personally, I believe the answer is 'no', because original order is lost in binaries, so... how can I implement the task?

推荐答案

这是具有自定义属性的版本:

Here is version with custom attribute:

[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();

这篇关于在声明顺序中排序枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆