如何在 VB.NET 中解析字符串以枚举值?
例如,我有这个枚举:
Public Enum Gender NotDefined Male Female End Enum
如何将字符串“男性”转换为 Gender枚举的 Male值?
Gender
Male
参见 Enum. TryParse。
Dim val = DirectCast([Enum].Parse(GetType(Gender), "Male"), Gender)
如何将字符串“男性”转换为性别枚举的“男性”值?
接受的解决方案返回一个 Enum 对象:
dim MyGender as string = "Male" dim Value as integer Value = DirectCast([Enum].Parse(GetType(Gender), MyGender), Integer)
也可以这样做:
value = cInt([enum].Parse(GetType(Gender), MyGender))
如果希望解析不区分大小写,可以使用以下方法:
[Enum].Parse(Gender, DirectCast(MyGender, String), True)
这将处理 dim MyGender as string = "Male"或 dim MyGender as string = "male"
dim MyGender as string = "Male"
dim MyGender as string = "male"