问题

如何在C#中将int转换为enum?

  最佳答案

从字符串:

 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.")
 

从int:

 YourEnum foo = (YourEnum)yourInt;
 

更新:

也可以从数字中

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

  相同标签的其他问题

c#enumscasting