2011-02-03 77 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()。