Parse a string to an Enum value in VB.NET

后端 未结 4 1618
难免孤独
难免孤独 2020-12-01 01:43

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

4条回答
  •  一个人的身影
    2020-12-01 02:19

    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))
    

提交回复
热议问题