vb.net 获取作为泛型的枚举的整数值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/378801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the Integer value of an enumeration which is a generic
提问by Ross Goddard
Here is the basic situation.
这是基本情况。
Public Class MyEnumClass(of T)
Public MyValue as T
End Class
This is vast oversimplification of the actual class, but basically I know that T is an enumeration (if it is not then there will be many other problems, and is a logical error made by the programmer)
这是对实际类的极大简化,但基本上我知道 T 是一个枚举(如果不是,那么会有很多其他问题,并且是程序员犯的逻辑错误)
Basically I want to get the underlying integer value of MyValue.
基本上我想获得 MyValue 的底层整数值。
Using Cint or Ctype, does not work.
使用 Cint 或 Ctype,不起作用。
回答by joshperry
I was going to use a cool piece of reflection code but just a simple Convert.ToInt32
works great... Forgive my VB I'm a C# guy
我打算使用一段很酷的反射代码,但只是一个简单的Convert.ToInt32
作品很好......原谅我的 VB 我是一个 C# 家伙
Public Function GetEnumInt(Of T)(enumVal As T) As Integer
Return Convert.ToInt32(enumVal)
End Function
回答by Ross Goddard
I tried this and it worked:
我试过了,它奏效了:
String.Format("{0:d}", MyValue)
回答by Jason Down
I know you can do the following to get all the underlying values (I hope my VB syntax is correct... I've been working in C# mostly of late):
我知道您可以执行以下操作来获取所有基础值(我希望我的 VB 语法是正确的……我最近一直在使用 C#):
Dim intVal As Integer
For Each intVal In [Enum].GetValues(GetType(T))
//intValue is now the enum integer value
Next
That might at least get you started in the right direction.
这至少可以让你朝着正确的方向开始。
回答by anefeletos
This also works :
Fix(enumval)
这也有效:
Fix(enumval)
回答by Glen Little
Another simple way in VB.NET is to add it to 0:
VB.NET 中的另一种简单方法是将其添加到 0:
Dim intVal As Integer = 0 + myEnum
So, this should work:
所以,这应该有效:
Sub GetEnumInt(of T)(enumVal as T) as Int
return 0 + enumVal
End Sub
回答by Leon Rom
Thanks to 'Jon Skeet'. But his code does not work in my Excel-2016. Minwhile the next code works fine:
感谢'乔恩斯基特'。但是他的代码在我的 Excel-2016 中不起作用。下一个代码可以正常工作:
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