在C#中如何将一个int
类型转换为enum
类型?
从整数类型:
YourEnum foo = (YourEnum)yourInt;
从字符串类型:
YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);
// 对于带有[Flags]属性的枚举,foo.ToString().Contains(",")检查是必要的。
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
{
throw new InvalidOperationException(
$"{yourString}不是YourEnum枚举的基础值。"
);
}
从数字类型:
YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum), yourInt);
标签:C#,Enum,YourEnum,int,枚举,foo
From: https://www.cnblogs.com/xiaomandujia/p/17781293.html