0

我有一个像这样的枚举:

public enum BlahType
{
    blahA = 1,
    blahB = 2,
    blahC = 3
}

如果我有一个值为“blahB”的字符串,是否可以将其与枚举 BlahType 进行强制转换以获得值 2?

4

6 回答 6

5

利用:

BlahType yourEnumValue = (BlahType) Enum.Parse(typeof(BlahType), "blahB");

接着

int yourIntValue = (int) yourEnumValue;
于 2009-04-07T15:59:01.593 回答
1

您可以使用Enum.Parse方法,然后强制转换为 int。

于 2009-04-07T15:56:50.397 回答
1
enum test
{
   VAL1,
   VAL2
}

static void Main(string[] args)
{
   test newTest = (test)Enum.Parse(typeof(test), "VAL2");
   Console.WriteLine(newTest.ToString());
}
于 2009-04-07T16:00:30.453 回答
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>";

 }
于 2009-04-07T15:59:35.057 回答
0

使用此代码...

BlahType blah = Enum.Parse(typeof(BlahType), "blahB");
于 2009-04-07T16:02:34.580 回答
0

如上所述,您希望使用的其他一些人:

        BlahType myEnum = (BlahType)Enum.Parse(typeof(BlahType), "blahB");
        int myEnumValue = (int)myEnum;
于 2009-04-07T16:14:51.510 回答