有这样一个枚举:如何分配枚举值的字符串变量
enum Items { one, two, three, four};
我如何分配结果字符串变量像
string itemType = Items.2;
或
string itemType = Items.one;
你可以让我知道,如果有可能吗?谢谢
有这样一个枚举:如何分配枚举值的字符串变量
enum Items { one, two, three, four};
我如何分配结果字符串变量像
string itemType = Items.2;
或
string itemType = Items.one;
你可以让我知道,如果有可能吗?谢谢
可以使用Enum.GetName
方法。
var name = Enum.GetName(typeof (Items), Items.one);
或者:
var name = Enum.GetName(typeof (Items), 0);
这绝对是更好的解决方案,因为您可以使用类似的语法向后退出:'Enum.Parse(typeof(Items),name)' – wizulus
致电ToString()
上的枚举。您应该可以执行Items.one.ToString()
并获取枚举的字符串表示形式。
加上`的ToString()到您的代码:
string itemType = Items.one.ToString();
'Items.one.ToString()'? –
你想要字符串名称为“one”还是基础数值为“1”? –