Implementation of Enum.TryParse in .NET 3.5

后端 未结 4 339
执念已碎
执念已碎 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

    It won't be a static method on Enum (static extension methods don't quite make sense), but it should work

    public static class EnumHelpers
    {
        public static bool TryParse(string value, out TEnum result)
            where TEnum : struct
        {
            try
            {
                result = (TEnum)Enum.Parse(typeof(TEnum), value); 
            }
            catch
            {
                result = default;
                return false;
            }
    
            return true;
        }
    }
    

提交回复
热议问题