[英]Converting string to enum?
I have the following enum in my class: 我班上有以下枚举:
public enum InventoryType
{
EQUIP = 1,
USE = 2,
SETUP = 3,
ETC = 4,
CASH = 5,
EVAN = 6,
TOTEMS = 7,
ANDROID = 8,
BITS = 9,
MECHANIC = 10,
HAKU = 11,
EQUIPPED = -1
}
Now, I have a field: 现在,我有一个领域:
public InventoryType InventoryType { get; private set; }
I load the data from MySql. 我从MySql加载数据。 MySql's column of type has the string that is the InventoryType.
MySql的类型列具有InventoryType的字符串。 How can I convert the string I get to the enum InventoryType?
如何将我得到的字符串转换为枚举InventoryType?
I tried: 我试过了:
this.InventoryType = reader.GetString("type");
But of course, that doesn't work, because it's getting a string and required an InventoryType. 但是,当然,这不起作用,因为它获得了一个字符串并需要一个InventoryType。 What can I do to convert it?
我该怎么做才能转换它? Thanks.
谢谢。
You can parse it using Enum.TryParse
: 您可以使用
Enum.TryParse
解析它:
InventoryType inventoryType;
if(Enum.TryParse(reader.GetString("type"), out inventoryType))
{
//use inventoryType
}
else
{
//not valid
}
You can use Enum.Parse
to parse your string back to Enum value - 您可以使用
Enum.Parse
将您的字符串解析回Enum值 -
this.InventoryType = (InventoryType)Enum.Parse(typeof(InventoryType),
reader.GetString("type"));
Also, use Parse
if you are sure the value will be valid; 另外,如果您确定该值有效,请使用
Parse
; otherwise use TryParse
. 否则使用
TryParse
。
尝试这个:-
this.InventoryType= (InventoryType) Enum.Parse( typeof(InventoryType), reader.GetString("type") );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.