2010-04-13 69 views
3

我有一個枚舉如何檢索一個枚舉的整數值?

public enum Color 
{ 
    Red = 0, 
    Blue = 1, 
    Yellow = 2 
} 

當我這樣做:

Color color = Color.Blue; 
Console.Writeline(color.Value); 

我想看到它的整數值(1在這種情況下),但它輸出「藍色」來代替。

我該如何解決這個問題?

我使用.NET 3.5。

回答

10

您可以強制轉換爲int:

Console.Writeline((int)color.Value); 
+0

OMG! 10 Upvotes ??? – Amsakanna 2010-04-13 08:24:42

0
Enum.Parse(typeof(Color), "Blue", true); 
+2

OP想要獲取特定枚舉值的整數值,而不是將某些字符串轉換爲枚舉值。 – Joey 2010-04-13 07:39:06

3
int value = Convert.ToInt32(Color.Blue);