Enum.Parse(), surely a neater way?

前端 未结 5 1946
猫巷女王i
猫巷女王i 2020-12-14 05:32

Say I have an enum,

public enum Colours
{
    Red,
    Blue
}

The only way I can see of parsing them is doing something like:



        
5条回答
  •  时光说笑
    2020-12-14 05:52

    If I'm parsing a "trusted" enum, then I use Enum.Parse().
    By "trusted" I mean, I know it will ALWAYS be a valid enum without ever erroring... ever!

    But there are times when "you never know what you're gonna get", and for those times, you need to use a nullable return value. Since .net doesn't offer this baked in, you can roll your own. Here's my recipe:

    public static TEnum? ParseEnum(string sEnumValue) where TEnum : struct
    {
        TEnum eTemp;
        TEnum? eReturn = null;
        if (Enum.TryParse(sEnumValue, out eTemp) == true)
            eReturn = eTemp;
        return eReturn;
    }
    

    To use this method, call it like so:

    eColor? SelectedColor = ParseEnum("Red");
    

    Just add this method to a class you use to store your other commonly used utility functions.

提交回复
热议问题