如何为的TryParse枚举值? [英] How to TryParse for Enum value?

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

问题描述

我想写这可以验证一个给定的值(作为字符串传递)针对的枚举可能值的功能。在匹配的情况下,它应该返回枚举实例;否则,它应该返回一个默认值。

该功能可能无法在内部使用尝试 / ,其中不包括使用枚举。解析,给定一个无效的参数时会抛出异常。

我想使用沿着的TryParse 功能线的东西来实现这一点:

 公共静态TEnum ToEnum< TEnum>(这个字符串strEnumValue,TEnum设置defaultValue)
{
   反对enumValue;
   如果(!的TryParse(typeof运算(TEnum),strEnumValue,出enumValue))
   {
       返回设置defaultValue;
   }
   返回(TEnum)enumValue;
}


解决方案

正如其他人所说,你要实现你自己的的TryParse 。西蒙Mourier是提供一个全面实施这需要所有的事情。

如果您使用的是位域枚举(如标志),你还必须处理诸如字符串MyEnum.Val1 | MyEnum.Val2这是两个组合枚举值。如果你只需要调用 Enum.IsDefined 以该字符串,它会返回false,尽管 Enum.Parse 正确处理它

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.

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

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

解决方案

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

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.

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

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