使用扩展方法将枚举转换为整数数组

时间:2013-07-26 07:22:23

标签: vb.net generics extension-methods enumeration

假设有一个枚举:

Public Enum MyEnum
    Value1 = 100
    Value2 = 200
    Value3 = 300
End Enum

如何实现扩展方法以获取此枚举的所有值的整数数组?

Dim ints As Integer() = GetType(MyEnum).ToIntArray()
' result: ints = {100, 200, 300}

(我已经看到扩展方法必须基于类型。)

1 个答案:

答案 0 :(得分:1)

<System.Runtime.CompilerServices.Extension()> _
Public Function ToIntArray(Of T As Type)(a As T) As Integer()
    Return [Enum].GetValues(a).Cast(Of Integer)().ToArray
End Function