在 VB.NET 中将字符串解析为 Enum 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/852141/
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
Parse a string to an Enum value in VB.NET
提问by jerbersoft
How can I parse a string in VB.NET to enum value?
如何将 VB.NET 中的字符串解析为枚举值?
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?
如何将字符串“Male”转换为Gender
枚举的Male
值?
回答by Kamarey
Dim val = DirectCast([Enum].Parse(GetType(Gender), "Male"), Gender)
回答by Anton Gogolev
See Enum.TryParse.
请参阅Enum.TryParse。
回答by Max Hodges
how can I convert a string "Male" to the Gender enum's Male value?
如何将字符串“Male”转换为 Gender 枚举的 Male 值?
The accepted solution returns an Enum object. To return the value you want this solution:
接受的解决方案返回一个 Enum 对象。要返回您想要此解决方案的值:
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))
回答by e.gad
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"
这将处理dim MyGender as string = "Male"
或dim MyGender as string = "male"