我有一个类似的枚举:
public enum BlahType
{
blahA = 1,
blahB = 2,
blahC = 3
}
如果我有一个值为'blahB'的字符串,是否可以将其强制转换为枚举BlahType以获取值2?
答案 0 :(得分:5)
使用:
BlahType yourEnumValue = (BlahType) Enum.Parse(typeof(BlahType), "blahB");
然后
int yourIntValue = (int) yourEnumValue;
答案 1 :(得分:1)
您可以使用Enum.Parse方法,然后转换为int。
答案 2 :(得分:1)
enum test
{
VAL1,
VAL2
}
static void Main(string[] args)
{
test newTest = (test)Enum.Parse(typeof(test), "VAL2");
Console.WriteLine(newTest.ToString());
}
答案 3 :(得分:0)
public void EnumInstanceFromString()
{
DayOfWeek wednesday = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "Wednesday");
DayOfWeek sunday = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "sunday", true);
DayOfWeek tgif = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "FRIDAY", true);
lblOutput.Text = wednesday.ToString() +
". Int value = " +
(int)wednesday).ToString() + "<br>";
lblOutput.Text += sunday.ToString() +
". Int value = " +
((int)sunday).ToString() + "<br>";
lblOutput.Text += tgif.ToString() +
". Int value = " +
((int)tgif).ToString() + "<br>";
}
答案 4 :(得分:0)
使用此代码...
BlahType blah = Enum.Parse(typeof(BlahType), "blahB");
答案 5 :(得分:0)
如上所述,您可能希望使用其他一些内容:
BlahType myEnum = (BlahType)Enum.Parse(typeof(BlahType), "blahB");
int myEnumValue = (int)myEnum;