How can I cast int to enum?

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

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

30条回答
  •  隐瞒了意图╮
    2020-11-22 01:05

    From an int:

    YourEnum foo = (YourEnum)yourInt;
    

    From a string:

    YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);
    
    // The foo.ToString().Contains(",") check is necessary for enumerations marked with an [Flags] attribute
    if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
    {
        throw new InvalidOperationException($"{yourString} is not an underlying value of the YourEnum enumeration.")
    }
    

    Update:

    From number you can also

    YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum) , yourInt);
    

提交回复
热议问题