How to TryParse for Enum value?

前端 未结 14 1004
终归单人心
终归单人心 2020-11-29 00:22

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 th

14条回答
  •  星月不相逢
    2020-11-29 00:27

    In the end you have to implement this around Enum.GetNames:

    public bool TryParseEnum(string str, bool caseSensitive, out T value) where T : struct {
        // Can't make this a type constraint...
        if (!typeof(T).IsEnum) {
            throw new ArgumentException("Type parameter must be an enum");
        }
        var names = Enum.GetNames(typeof(T));
        value = (Enum.GetValues(typeof(T)) as T[])[0];  // For want of a better default
        foreach (var name in names) {
            if (String.Equals(name, str, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)) {
                value = (T)Enum.Parse(typeof(T), name);
                return true;
            }
        }
        return false;
    }
    

    Additional notes:

    • Enum.TryParse is included in .NET 4. See here http://msdn.microsoft.com/library/dd991876(VS.100).aspx
    • Another approach would be to directly wrap Enum.Parse catching the exception thrown when it fails. This could be faster when a match is found, but will likely to slower if not. Depending on the data you are processing this may or may not be a net improvement.

    EDIT: Just seen a better implementation on this, which caches the necessary information: http://damieng.com/blog/2010/10/17/enums-better-syntax-improved-performance-and-tryparse-in-net-3-5

提交回复
热议问题