問題

如何在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