Parse a string to an Enum value in VB.NET

2019-01-10 12:35发布

问题:

How can I parse a string in VB.NET to enum value?

Example I have this enum:

Public Enum Gender
    NotDefined
    Male
    Female
End Enum

how can I convert a string "Male" to the Gender enum's Male value?

回答1:

Dim val = DirectCast([Enum].Parse(GetType(Gender), "Male"), Gender)


回答2:

See Enum.TryParse.



回答3:

how can I convert a string "Male" to the Gender enum's Male value?

The accepted solution returns an Enum object. To return the value you want this solution:

dim MyGender as string = "Male"
dim Value as integer
Value = DirectCast([Enum].Parse(GetType(Gender), MyGender), Integer)

Can also do it this way:

value = cInt([enum].Parse(GetType(Gender), MyGender))


回答4:

If you want the parse to be case insensitive, you can use the following:

[Enum].Parse(Gender, DirectCast(MyGender, String), True)

This will handle dim MyGender as string = "Male" or dim MyGender as string = "male"



标签: vb.net enums