Enum.Parse()具体如何使用?

如题所述

将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。

比方说有个枚举

enum money { RMB , USD}

你想把 "RMB"字符串或者 数字0转为 money枚举,就可以
(money)Enum.Parse(typeof(money), "RMB");
(money)Enum.Parse(typeof(money), 0);

要注意前面还要加强制类型转换,因为Parse出来的是Enum基类。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-06-22
将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。

using System;

public class ParseTest
{
[FlagsAttribute]
enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };

public static void Main()
{
Console.WriteLine("The entries of the Colors Enum are:");
foreach (string colorName in Enum.GetNames(typeof(Colors)))
{
Console.WriteLine("{0}={1}", colorName,
Convert.ToInt32(Enum.Parse(typeof(Colors), colorName)));
}
Console.WriteLine();
Colors myOrange = (Colors)Enum.Parse(typeof(Colors), "Red, Yellow");
Console.WriteLine("The myOrange value {1} has the combined entries of {0}",
myOrange, Convert.ToInt64(myOrange));
}
}

/*
This code example produces the following results:

The entries of the Colors Enum are:
Red=1
Green=2
Blue=4
Yellow=8

The myOrange value 9 has the combined entries of Red, Yellow

*/本回答被网友采纳
相似回答