Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
854 views
in Technique[技术] by (71.8m points)

.net - Enum.TryParse with Flags attribute

I have written code to TryParse enum either by value or by its name as shown below. How can I extend this code to include parsing enums with Flags attribute?

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

Currently this code works for the following enums:

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"

Does not work for:

[Flags]
enum SomeEnum2 { A = 1, B = 2, C = 4 } // can parse either by 'A' or 'a'
// cannot parse for A|B

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Flags enums are written using , by using the .Net convention and not |. Enum.Parse() works perfectly when using ',' strings:

[Flags]
public enum Flags
{
    A = 1,
    B = 2,
    C = 4,
    D = 8,
}

var enumString =  (Flags.A | Flags.B | Flags.C).ToString();
Console.WriteLine(enumString); // Outputs: A, B, C
Flags f = (Flags)Enum.Parse(typeof(Flags),  enumString);
Console.WriteLine(f); // Outputs: A, B, C

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...