如何尝试稀释枚举值? [英] How to TryParse for Enum value?

查看:123
本文介绍了如何尝试稀释枚举值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个函数,它可以验证一个给定的值(以字符串的形式传递),而不是可能的值枚举。在匹配的情况下,它应该返回枚举实例;

I want to write a function which can validate a given value (passed as a string) against possible values of an enum. In the case of a match, it should return the enum instance; otherwise, it should return a default value.

该函数内部不能使用 try / catch ,其中不包括使用 Enum.Parse ,在给出无效参数时会引发异常。

The function may not internally use try/catch, which excludes using Enum.Parse, which throws an exception when given an invalid argument.

我想使用一些 TryParse 函数来实现这一点:

I'd like to use something along the lines of a TryParse function to implement this:

public static TEnum ToEnum<TEnum>(this string strEnumValue, TEnum defaultValue)
{
   object enumValue;
   if (!TryParse (typeof (TEnum), strEnumValue, out enumValue))
   {
       return defaultValue;
   }
   return (TEnum) enumValue;
}


推荐答案

正如其他人所说,你必须实现自己的 TryParse 。 Simon Mourier正在提供一个完整的实现,负责处理所有的事情。

As others have said, you have to implement your own TryParse. Simon Mourier is providing a full implementation which takes care of everything.

如果您使用位域枚举(即标志),则还必须处理像MyEnum.Val1 | MyEnum.Val2它是两个枚举值的组合。如果您使用此字符串调用 Enum.IsDefined ,则它将返回false,即使 Enum.Parse 正确处理它

If you are using bitfield enums (i.e. flags), you also have to handle a string like "MyEnum.Val1|MyEnum.Val2" which is a combination of two enum values. If you just call Enum.IsDefined with this string, it will return false, even though Enum.Parse handles it correctly.

更新

正如Lisa和Christian在评论中所提到的, code> Enum.TryParse 现在可用于.NET4及以上版本的C#。


MSDN文件

As mentioned by Lisa and Christian in the comments, Enum.TryParse is now available for C# in .NET4 and up.

MSDN Docs

这篇关于如何尝试稀释枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆