【问题标题】:Get the Integer value of an enumeration which is a generic获取泛型枚举的整数值
【发布时间】:2008-12-18 18:48:57
【问题描述】:

这是基本情况。

Public Class MyEnumClass(of T)
   Public MyValue as T
End Class

这是对实际类的极大过度简化,但基本上我知道 T 是一个枚举(如果不是那么会有很多其他问题,并且是程序员犯的逻辑错误)

基本上我想获取 MyValue 的底层整数值。

使用 Cint 或 Ctype,不起作用。

【问题讨论】:

  • 我将枚举完全误读为 IEnumerable :(

标签: vb.net generics enums


【解决方案1】:

我打算使用一段很酷的反射代码,但一个简单的 Convert.ToInt32 效果很好...原谅我的 VB 我是 C# 人

Public Function GetEnumInt(Of T)(enumVal As T) As Integer
    Return Convert.ToInt32(enumVal)
End Function

【讨论】:

    【解决方案2】:

    我试过了,效果很好:

    String.Format("{0:d}", MyValue)
    

    【讨论】:

    • 嗯,把它转换成一个字符串 - 我以为你想要它作为一个整数?
    【解决方案3】:

    我知道您可以执行以下操作来获取所有基础值(我希望我的 VB 语法是正确的……我最近大部分时间都在使用 C#):

    Dim intVal As Integer
    
    For Each intVal In  [Enum].GetValues(GetType(T))
        //intValue is now the enum integer value
    Next
    

    这至少可以让你朝着正确的方向开始。

    【讨论】:

      【解决方案4】:

      这也有效: Fix(enumval)

      【讨论】:

        【解决方案5】:

        VB.NET 中另一种简单的方法是将其添加到 0:

        Dim intVal As Integer = 0 + myEnum
        

        所以,这应该可行:

        Sub GetEnumInt(of T)(enumVal as T) as Int
           return 0 + enumVal
        End Sub
        

        【讨论】:

        • 这在myEnum是泛型参数类型时不起作用,因为编译器不知道它是否真的是一个枚举,因此不会对运算符+进行类型检查。跨度>
        【解决方案6】:

        感谢“乔恩·斯基特”。但他的代码在我的 Excel-2016 中不起作用。 Minwhile 下一个代码工作正常:

        Public Enum TypOfProtectWs
            pws_NotFound = 0
            pws_AllowAll = 1
            pws_AllowFormat = 2
            pws_AllowNone = 3
        End Enum
        
        Private Function TypOfProtectWs2I(pws As TypOfProtectWs) As Integer
            TypOfProtectWs2I = Format("0", pws)
        End Function
        
        Private Sub test_TypOfProtectWs2I()
            Debug.Print TypOfProtectWs2I(pws_AllowAll)
        End Sub
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多