Implementation of Enum.TryParse in .NET 3.5

后端 未结 4 424
执念已碎
执念已碎 2021-01-12 14:34

How could I implement the .NET 4\'s Enum.TryParse method in .NET 3.5?

public static bool TryParse(string          


        
4条回答
  •  情书的邮戳
    2021-01-12 15:02

    At NLog we also needed Enum.TryParse for .Net 3.5. We have implemented the basic features (just parse, case sensitive and insensitive, no flags) influenced by this post.

    This basic implementation is highly unit tested so it has the same behavior as Microsoft`s .Net 4 implementation.

    /// 
    /// Enum.TryParse implementation for .net 3.5 
    /// 
    /// 
    /// 
    /// Don't uses reflection
    // ReSharper disable once UnusedMember.Local
    private static bool TryParseEnum_net3(string value, bool ignoreCase, out TEnum result) where TEnum : struct
    {
        var enumType = typeof(TEnum);
        if (!enumType.IsEnum())
            throw new ArgumentException($"Type '{enumType.FullName}' is not an enum");
    
        if (StringHelpers.IsNullOrWhiteSpace(value))
        {
            result = default(TEnum);
            return false;
        }
    
        try
        {
            result = (TEnum)Enum.Parse(enumType, value, ignoreCase);
            return true;
        }
        catch (Exception)
        {
            result = default(TEnum);
            return false;
        }
    }
    
    

    And is using:

    public static class StringHelpers
    {
        /// 
        /// IsNullOrWhiteSpace, including for .NET 3.5
        /// 
        /// 
        /// 
        [ContractAnnotation("value:null => true")]
        internal static bool IsNullOrWhiteSpace(string value)
        {
    #if NET3_5
    
            if (value == null) return true;
            if (value.Length == 0) return true;
            return String.IsNullOrEmpty(value.Trim());
    #else
            return string.IsNullOrWhiteSpace(value);
    #endif
        }
    }
    

    The code can be found at the NLog GitHub, and also the unit tests are on GitHub (xUnit)

提交回复
热议问题