Enum from string, int, etc

后端 未结 7 944
伪装坚强ぢ
伪装坚强ぢ 2021-01-17 07:23

Using extension method we can create methods to convert an enum to other datatype like string, int by creating extension methods ToInt(), ToString()

7条回答
  •  一生所求
    2021-01-17 08:05

    The other way around would be possibly... the other way around ;) Extend int and string with generic extension methods which will take as type parameter the type of an enum:

    public static TEnum ToEnum(this int val)
    {
        return (TEnum) System.Enum.ToObject(typeof(TEnum), val);
    }
    

    public static TEnum ToEnum(this string val)
    {
        return (TEnum) System.Enum.Parse(typeof(TEnum), val);
    }
    

    Usage:

    var redFromInt = 141.ToEnum();
    var redFromString = "Red".ToEnum();
    

    There is unfortunately no generic constraint for Enums, so we have to check TEnum type during runtime; to simplify we'll leave that verification to Enum.ToObject and Enum.Parse methods.

提交回复
热议问题