Enum.Parse(),肯定是一个更简洁的方式?

max*_*axp 60 c# asp.net enums

说我有一个枚举,

public enum Colours
{
    Red,
    Blue
}
Run Code Online (Sandbox Code Playgroud)

我能看到解析它们的唯一方法就是:

string colour = "Green";
var col = (Colours)Enum.Parse(typeOf(Colours),colour);
Run Code Online (Sandbox Code Playgroud)

这将抛出System.ArgumentException,因为"Green"不是Colours枚举的成员.

现在我真的很讨厌在try/catch中包装代码,有没有更简洁的方法来做这个不涉及我迭代每个Colours枚举,并进行字符串比较colour

sta*_*son 57

Enum.IsDefined()首先使用,以避免包装在try/catch中.它将返回一个布尔值,表示输入是否是该枚举的有效成员.

  • 这不起作用-区分大小写 (2认同)

Sky*_*ers 41

我相信4.0有Enum.TryParse

否则使用扩展方法:

public static bool TryParse<T>(this Enum theEnum, string valueToParse, out T returnValue)
{
    returnValue = default(T);
    int intEnumValue;
    if (Int32.TryParse(valueToParse, out intEnumValue))
    {
        if (Enum.IsDefined(typeof(T), intEnumValue))
        {
            returnValue = (T)(object)intEnumValue;
            return true;
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)


Stu*_*tLC 8

只是为了扩展Sky的.Net 4 Enum.TryParse <>的链接,即

Enum.TryParse<TEnum>(
    string value,
    [bool ignoreCase,]
    out TEnum result
)
Run Code Online (Sandbox Code Playgroud)

这可以使用如下:

    enum Colour
    {
        Red,
        Blue
    }

    private void ParseColours()
    {
        Colour aColour;

        // IMO using the actual enum type is intuitive, but Resharper gives 
        // "Access to a static member of a type via a derived type"
        if (Colour.TryParse("RED", true, out aColour))
        {
           // ... success
        }

        // OR, the compiler can infer the type from the out
        if (Enum.TryParse("Red", out aColour))
        {
           // ... success
        }

        // OR explicit type specification
        // (Resharper: Type argument specification is redundant)
        if (Enum.TryParse<Colour>("Red", out aColour))
        {
          // ... success
        }
    }
Run Code Online (Sandbox Code Playgroud)


ito*_*son 6

不,这没有"没有投掷"的方法(其他一些类的tryParse).

但是,您可以轻松编写自己的代码,以便将try-catch逻辑(或IsDefined检查)封装在一个帮助程序方法中,这样它就不会污染您的应用程序代码:

public static object TryParse(Type enumType, string value, out bool success)
{
  success = Enum.IsDefined(enumType, value);
  if (success)
  {
    return Enum.Parse(enumType, value);
  }
  return null;
}
Run Code Online (Sandbox Code Playgroud)


Mik*_*Vee 6

如果我正在解析" 受信任的 "枚举,那么我使用Enum.Parse().
通过" 信任 ",我的意思是,我知道它永远是一个有效的枚举,而不会错过......永远!

但有时候" 你永远不会知道你会得到什么 ",而且在那些时候,你需要使用可以为空的回报值.由于.net不提供这种烘焙,你可以自己动手.这是我的食谱:

public static TEnum? ParseEnum<TEnum>(string sEnumValue) where TEnum : struct
{
    TEnum eTemp;
    TEnum? eReturn = null;
    if (Enum.TryParse<TEnum>(sEnumValue, out eTemp) == true)
        eReturn = eTemp;
    return eReturn;
}
Run Code Online (Sandbox Code Playgroud)

要使用此方法,请像这样调用它:

eColor? SelectedColor = ParseEnum<eColor>("Red");
Run Code Online (Sandbox Code Playgroud)

只需将此方法添加到用于存储其他常用实用程序函数的类中.