Implementation of Enum.TryParse in .NET 3.5

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

    I dislike using a try-catch to handle any conversion failures or other non-exceptional events as part of the normal flow of my application, so my own Enum.TryParse method for .NET 3.5 and earlier makes use of the Enum.IsDefined() method to make sure the there will not be an exception thrown by Enum.Parse(). You can also include some null checks on value to prevent an ArgumentNullException if value is null.

    public static bool TryParse(string value, out TEnum result)
        where TEnum : struct, IConvertible
    {
        var retValue = value == null ? 
                    false : 
                    Enum.IsDefined(typeof(TEnum), value);
        result = retValue ?
                    (TEnum)Enum.Parse(typeof(TEnum), value) :
                    default(TEnum);
        return retValue;
    }
    

    Obviously this method will not reside in the Enum class so you will need a class to include this in that would be appropriate.

    One limitation is the lack of an enum constraint on generic methods, so you would have to consider how you want to handle incorrect types. Enum.IsDefined will throw an ArgumentException if TEnum is not an enum but the only other option is a runtime check and throwing a different exception, so I generally do not add an additional check and just let the type checking in these methods handle for me. I'd consider adding IConvertible as another constraint, just to help constrain the type even more.

提交回复
热议问题