我有一个像这样的枚举:
public enum BlahType
{
blahA = 1,
blahB = 2,
blahC = 3
}
如果我有一个值为“blahB”的字符串,是否可以将其与枚举 BlahType 进行强制转换以获得值 2?
我有一个像这样的枚举:
public enum BlahType
{
blahA = 1,
blahB = 2,
blahC = 3
}
如果我有一个值为“blahB”的字符串,是否可以将其与枚举 BlahType 进行强制转换以获得值 2?
利用:
BlahType yourEnumValue = (BlahType) Enum.Parse(typeof(BlahType), "blahB");
接着
int yourIntValue = (int) yourEnumValue;
您可以使用Enum.Parse方法,然后强制转换为 int。
enum test
{
VAL1,
VAL2
}
static void Main(string[] args)
{
test newTest = (test)Enum.Parse(typeof(test), "VAL2");
Console.WriteLine(newTest.ToString());
}
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>";
}
使用此代码...
BlahType blah = Enum.Parse(typeof(BlahType), "blahB");
如上所述,您希望使用的其他一些人:
BlahType myEnum = (BlahType)Enum.Parse(typeof(BlahType), "blahB");
int myEnumValue = (int)myEnum;