从应用程序的另一层,我可以得到枚举类型的名称和整数值。我如何使用这些数据来获取该枚举值的字符串表示。
例如,如果我有一个枚举:
public enum Cheese
{
Edam = 1,
Cheddar = 3,
Brie = 201,
RedLeicester = 1001
}
我可用的数据为
string dataType = "Cheese";
int dataValue = 3;
我该如何获取结果:
"Cheddar"
从应用程序的另一层,我可以得到枚举类型的名称和整数值。我如何使用这些数据来获取该枚举值的字符串表示。
例如,如果我有一个枚举:
public enum Cheese
{
Edam = 1,
Cheddar = 3,
Brie = 201,
RedLeicester = 1001
}
我可用的数据为
string dataType = "Cheese";
int dataValue = 3;
"Cheddar"
除了枚举本身的名称,您还需要知道声明枚举的命名空间和程序集。假设您在定义枚举的程序集中运行以下代码,并且所有枚举都在您在编译时知道的相同命名空间中定义,您可以这样做:
string dataType = "Cheese";
int dataValue = 3;
var enumType = Type.GetType("Namespaces.Of.Your.Enums." + dataType);
var name = Enum.GetName(enumType, dataValue);
Type t = Type.GetType(dataType)
string value = Enum.GetName(t, dataValue)
在这里,enum.Parse() 将是你的好朋友。
像这样:
int cheeseType = 1;
(Cheese)Enum.Parse(typeof(Cheese), cheeseType.ToString());