我正在尝试编写一个通用的例程来从INT返回ENUM [英] I'm trying to write a generic routinue to return ENUM from INT
本文介绍了我正在尝试编写一个通用的例程来从INT返回ENUM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个通用例程,该例程将根据存储在DB中的INT值返回ENUM。
提前致谢
I'm trying to write a generic routine that will return an ENUM based on the INT value stored in the DB.
Thanks in advance
Imports System.ComponentModel
Imports System.Reflection
Public Enum enColour
<Description("BLUE")> clBlue = 1
<Description("RED")> clRed = 2
<Description("GREEN")> clGreen = 3
End Enum
Public Enum enCarMake
<Description("Ford")> cmFord = 1
<Description("Toyota")> cmToyota = 2
<Description("Skoda")> cmSkoda = 3
End Enum
Public Sub LoadFromDB
Dim myENUMColour AS enColour
Dim myENUMMake As enCarMake
With rdrLoadFromTable
ReturnENUMFromInt(CInt(.Item("Colour")), myENUMColour)
ReturnENUMFromInt(CInt(.Item("CarMake")), myENUMMake)
End With
End Sub
Public Sub ReturnENUMFromInt(pIntValueFromDB AS Integer, pReturnValue AS [ENUM])
'LOOKING FOR HELP HERE...
pReturnValue = CType(pIntValueFromDB, pReturnValue.GetType)
End Sub;
推荐答案
创建自己的函数似乎有点过度杀戮为此,Enum.Parse
(或Enum.TryParse
)甚至CType
电话会为你做这件事。
但是如果你的情况是这样的,你需要一个通用的方法,那么这样的事可能会为你做的伎俩;
It seems a little over-kill to create your own function for doing this,Enum.Parse
(orEnum.TryParse
) or even aCType
call will do this for you.
But if your circumstances are such that you need a generic method for this, then maybe something like this will do the trick for you;
Module Module1
Public Enum Color
Red
Green
Blue
End Enum
Public Enum CarMake
Ford
Toyota
Skoda
End Enum
Sub Main()
Dim color As Color = ToEnum(Of Color)(1)
Dim carMake as CarMake ToEnum(Of CarMake)(2)
End Sub
Public Function ToEnum(Of T As Structure)(ByVal arg As Integer) As T
If [Enum].IsDefined(GetType(T), arg) Then
Return [Enum].Parse(GetType(T), arg.ToString())
Else
Throw New ArgumentException(String.Format("'{0}' is not defined in enumeration {1}", arg, GetType(T).FullName))
End If
End Function
End Module
希望这有帮助,
Fredrik
Hope this helps,
Fredrik
试试 Enum.TryParse [ ^ ],应该做你想做的事。
Try Enum.TryParse[^], should do what you want.
这篇关于我正在尝试编写一个通用的例程来从INT返回ENUM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文