【问题标题】:How to sort the result of Enum.GetValues without knowing the Enum itself如何在不知道 Enum 本身的情况下对 Enum.GetValues 的结果进行排序
【发布时间】:2019-03-16 14:13:49
【问题描述】:

我正在寻找一种按枚举值名称对[Enum].GetValues(enumType)(即Array)的结果进行排序的方法。

Public Enum TestEnum As Integer
    Zero = 0
    One = 1
    Two = 2
End Enum

我在编译时不知道枚举类型,所以我不能在 Array 上执行 Cast(Of...) 并在之后使用 OrderBy 扩展。

我在运行时只有一个Type 变量(称为enumType)。

Dim enumType As Type = GetType(TestEnum)   'just for testing
Dim values As Array = [Enum].GetValues(enumType)

values 数组包含 {Zero, One, Two},我正在寻找一种方法来获取 {One, Two, Zero}(按字母顺序)。请记住,您在编译时不知道TestEnum,您只有变量enumType。

【问题讨论】:

  • 使用 Enum.GetName() 获取您需要按字母顺序排序的字符串。

标签: .net generics enums


【解决方案1】:

我希望有一个更优雅的解决方案,但这样做可以:

Dim enumType As Type = GetType(TestEnum)
Dim names As String() = [Enum].GetNames(enumType)
Dim values As Array = names.OrderBy(Of String)(Function(x As String) x) _
                           .Select(Of Object)((Function(x As String) [Enum].Parse(enumType, x))) _
                           .ToArray

【讨论】:

    猜你喜欢
    • 2018-07-09
    • 2021-09-26
    • 2015-05-31
    • 2011-11-06
    • 2011-01-11
    • 2011-06-29
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    相关资源
    最近更新 更多