Enum.Parse(),肯定是一种更简洁的方法吗?

发布于 2024-08-24 12:47:34 字数 524 浏览 2 评论 0原文

假设我有一个枚举,

public enum Colours
{
    Red,
    Blue
}

我能看到解析它们的唯一方法是执行以下操作:

string colour = "Green";
var col = (Colours)Enum.Parse(typeOf(Colours),colour);

这将抛出 System.ArgumentException 因为“Green”不是 Colours 枚举的成员。

现在我真的很讨厌将代码包装在 try/catch 中,是否没有更简洁的方法来做到这一点,而不需要我迭代每个 Colours 枚举,并与 colour 进行字符串比较代码>?

Say I have an enum,

public enum Colours
{
    Red,
    Blue
}

The only way I can see of parsing them is doing something like:

string colour = "Green";
var col = (Colours)Enum.Parse(typeOf(Colours),colour);

This will throw a System.ArgumentException because "Green" is not a member of the Colours enum.

Now I really hate wrapping code in try/catch's, is there no neater way to do this that doesn't involve me iterating through each Colours enum, and doing a string comparison against colour?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

岁吢 2024-08-31 12:47:35

Use Enum.IsDefined() first, to save yourself from wrapping in a try/catch. It will return a boolean value of whether or not the input is a valid member of that enum.

江南月 2024-08-31 12:47:35

我相信 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;
}

I believe that 4.0 has Enum.TryParse

Otherwise use an extension method:

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;
}
寒尘 2024-08-31 12:47:35

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

Enum.TryParse<TEnum>(
    string value,
    [bool ignoreCase,]
    out TEnum result
)

可以这样使用:

    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
        }
    }

Just to expand on Sky's link to the .Net 4 Enum.TryParse<>, viz

Enum.TryParse<TEnum>(
    string value,
    [bool ignoreCase,]
    out TEnum result
)

This can be used as follows:

    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
        }
    }
听风念你 2024-08-31 12:47:35

不,没有“不抛出”方法(类似于其他一些类所具有的 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;
}

No, there's no "no-throw" method for this (a la TryParse that some other classes have).

However, you could easily write your own so as to encapsulate the try-catch logic (or the IsDefined check) in one helper method so it doesn't pollute your app code:

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;
}
素食主义者 2024-08-31 12:47:35

如果我正在解析“可信”枚举,那么我会使用 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;
}

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

eColor? SelectedColor = ParseEnum<eColor>("Red");

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

If I'm parsing a "trusted" enum, then I use Enum.Parse().
By "trusted" I mean, I know it will ALWAYS be a valid enum without ever erroring... ever!

But there are times when "you never know what you're gonna get", and for those times, you need to use a nullable return value. Since .net doesn't offer this baked in, you can roll your own. Here's my recipe:

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;
}

To use this method, call it like so:

eColor? SelectedColor = ParseEnum<eColor>("Red");

Just add this method to a class you use to store your other commonly used utility functions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文