您的位置:首页 > 其它

从String到enum的互换(string to enum to string)

2006-07-02 20:39 197 查看
Convert a string to an enumerated (enum) value.

Using the Enum.Parse method, you can easily convert a string value to an enumerated value. Doing this requires the type of the enum and string value. Adding the true argument will cause the case to be ignored.

Using the following enum for this example:

private enum Aircraft
{
Beech,
Cessna,
Piper
}

You can easily convert the string to an enum value like this:

 

Aircraft air = (Aircraft) Enum.Parse(typeof(Aircraft), "Cessna", true);

 

Ideally you should wrap a try-catch around the Enum.Parse statement.

 

string s;
s = air .ToString();
s = Enum.GetName(typeof(Aircraft), air.Beech);

后者比前者性能高
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: