How can I cast int to enum?

后端 未结 30 1491
礼貌的吻别
礼貌的吻别 2020-11-22 00:56

How can an int be cast to an enum in C#?

30条回答
  •  抹茶落季
    2020-11-22 01:23

    Alternatively, use an extension method instead of a one-liner:

    public static T ToEnum(this string enumString)
    {
        return (T) Enum.Parse(typeof (T), enumString);
    }
    

    Usage:

    Color colorEnum = "Red".ToEnum();
    

    OR

    string color = "Red";
    var colorEnum = color.ToEnum();
    

提交回复
热议问题