按声明顺序对枚举进行排序 [英] Sort enums in declaration order

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

问题描述

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

有什么方法可以按在 .cs 文件中声明的顺序对 Enum.GetValues(typeof(CurrencyId)).Cast() 的结果进行排序(USD、UAH、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天全站免登陆