2011-02-03 39 views
4

我將字符串類型的數值轉換爲相應的Enum。當我測試我的代碼時,我發現有趣的行爲讓我感到困惑。解析Enum時出現混亂

使用下面的代碼示例,有人可以闡明爲什麼在/ s當「s」變量的值與Enum值之一不匹配時不拋出異常?另外,如何將sEnum var設置爲Stooge枚舉定義中不存在的值?

class Program 
{ 
    enum Stooge 
    { 
     Unspecified, 
     Moe, 
     Larry, 
     Curly, 
     Shemp 
    } 

    static void Main(string[] args) 
    { 
     while (true) 
     { 
      Console.WriteLine("Enter a number..."); 

      string s = Console.ReadLine(); 
      Stooge sEnum = (Stooge)(int.Parse(s)); //Why doesn't this line throw if s != 0, 1, 2, 3, or 4? 

      Console.WriteLine("\r\nYou entered: {0}\r\nEnum String Value: {1}\r\nEnum Int Value: {2}\r\n", s, sEnum.ToString(), (int)sEnum); 
     } 
    } 
} 
+0

可能重複的[爲什麼將int轉換爲無效的枚舉值不拋出異常?](http://stackoverflow.com/questions/6413804/why-does-casting-int-to-invalid-enum-value-not -throw-exception) – nawfal 2013-12-01 19:39:11

回答

7

這是創建.NET的人的決定。一個枚舉由另一個值類型(intshort,byte等)支持,因此它實際上可以具有對這些值類型有效的任何值。

我個人沒有這種工作方式的風扇,所以我做了一系列的實用方法:

/// <summary> 
/// Utility methods for enum values. This static type will fail to initialize 
/// (throwing a <see cref="TypeInitializationException"/>) if 
/// you try to provide a value that is not an enum. 
/// </summary> 
/// <typeparam name="T">An enum type. </typeparam> 
public static class EnumUtil<T> 
    where T : struct, IConvertible // Try to get as much of a static check as we can. 
{ 
    // The .NET framework doesn't provide a compile-checked 
    // way to ensure that a type is an enum, so we have to check when the type 
    // is statically invoked. 
    static EnumUtil() 
    { 
     // Throw Exception on static initialization if the given type isn't an enum. 
     Require.That(typeof (T).IsEnum,() => typeof(T).FullName + " is not an enum type."); 
    } 

    /// <summary> 
    /// In the .NET Framework, objects can be cast to enum values which are not 
    /// defined for their type. This method provides a simple fail-fast check 
    /// that the enum value is defined, and creates a cast at the same time. 
    /// Cast the given value as the given enum type. 
    /// Throw an exception if the value is not defined for the given enum type. 
    /// </summary> 
    /// <typeparam name="T"></typeparam> 
    /// <param name="enumValue"></param> 
    /// <exception cref="InvalidCastException"> 
    /// If the given value is not a defined value of the enum type. 
    /// </exception> 
    /// <returns></returns> 
    public static T DefinedCast(object enumValue) 

    { 
     if (!System.Enum.IsDefined(typeof(T), enumValue)) 
      throw new InvalidCastException(enumValue + " is not a defined value for enum type " + 
              typeof (T).FullName); 
     return (T) enumValue; 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="enumValue"></param> 
    /// <returns></returns> 
    public static T Parse(string enumValue) 
    { 
     var parsedValue = (T)System.Enum.Parse(typeof (T), enumValue); 
     //Require that the parsed value is defined 
     Require.That(parsedValue.IsDefined(), 
      () => new ArgumentException(string.Format("{0} is not a defined value for enum type {1}", 
       enumValue, typeof(T).FullName))); 
     return parsedValue; 
    } 

    public static bool IsDefined(T enumValue) 
    { 
     return System.Enum.IsDefined(typeof (T), enumValue); 
    } 

} 

public static class EnumExtensions 
{ 
    public static bool IsDefined<T>(this T enumValue) 
     where T : struct, IConvertible 
    { 
     return EnumUtil<T>.IsDefined(enumValue); 
    } 
} 

這樣一來,我可以說:

if(!sEnum.IsDefined()) throw new Exception(...); 

...或:

EnumUtil<Stooge>.Parse(s); // throws an exception if s is not a defined value. 
+0

`Require.That`也來自我自己的圖書館。你可以用'if(!)拋出新的異常(...);' – StriplingWarrior 2011-02-03 22:47:05

+0

我喜歡這個Require.That你會分享你是如何做到的嗎? – 2014-04-28 00:01:01

2

一個枚舉在技術上只是一個int(或任何你已經定義的枚舉的基礎類型)。您可以在枚舉中檢查相應的值,但要調用Enum.IsDefined。更多的信息在這裏:Cast int to enum in C#

1

枚舉是真的薄包裝int。基本上它是int +可能值的靜態集合(常量的種類)。所有的檢查都在編譯時,類型檢查等。但是當你真的投intenum運行時不關心。所以驗證你的輸入!

-1

如果在傳遞的值不可解析的情況下不想拋出異常,則使用int.Parse()。如果不想分析可能無效的值而不拋出異常,則使用int.TryParse()。