开发者

Unable to retrieve the enum members in the order they have been defined!

We have an enum with members having random values, say

enum MyEnum
{
    enumMember1 = 100,
    enumMember2 = 10,
    enumMember3 = 50
}

We couldnt iterate through the enum members in the order they have been defined! Enum.GetValues and Enum.GetNames both internally sort the members and gives the result!

iterating the array returned by Enum.GetNames or Enum.GetValue开发者_如何学运维s and doing a .ToString() on each of the array elements gives us,

enumMember2, enumMember3, enumMember100. 

Was just wondering if there is any out of the box approach to get the enum members in the order they have been created? Did search, didnt get much info! Thanks!

P.S. I would hate to get this done through a custom attribute! And While drafting it, i had a doubt if the IL for enum gets generated after sorting the Enum members, going to check it ryt away!


You can use reflection:

var values = typeof(MyEnum).GetFields(BindingFlags.Public | BindingFlags.Static)
                 .Select (x => Enum.Parse(typeof(MyEnum), x.Name));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜