我已经编写了代码来TryParse
按值或按名称进行枚举,如下所示。如何扩展此代码以包含解析具有Flags
属性的枚举?
public static bool TryParse<T>(this T enum_type, object value, out T result)
where T : struct
{
return enum_type.TryParse<T>(value, true, out result);
}
public static bool TryParse<T>(this T enum_type,
object value, bool ignoreCase, out T result)
where T : struct
{
result = default(T);
var is_converted = false;
var is_valid_value_for_conversion = new Func<T, object, bool, bool>[]{
(e, v, i) => e.GetType().IsEnum,
(e, v, i) => v != null,
(e, v, i) => Enum.GetNames(e.GetType()).Any(n => String.Compare(n, v.ToString(), i) == 0) || Enum.IsDefined(e.GetType(), v)
};
if(is_valid_value_for_conversion.All(rule => rule(enum_type, value, ignoreCase))){
result = (T)Enum.Parse(typeof(T), value.ToString(), ignoreCase);
is_converted = true;
}
return is_converted;
}
目前,此代码适用于以下枚举:
enum SomeEnum{ A, B, C }
// can parse either by 'A' or 'a'
enum SomeEnum1 : int { A = 1, B = 2, C = 3 }
// can parse either by 'A' or 'a' or 1 or "1"
不适用于:
[Flags]
enum SomeEnum2 { A = 1, B = 2, C = 4 } // can parse either by 'A' or 'a'
// cannot parse for A|B
谢谢!