YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString); // 对于标记了 [Flags] 属性的枚举,需要检查 foo.ToString().Contains(",") if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(",")) { thrownew InvalidOperationException( $"{yourString} is not an underlying value of the YourEnum enumeration." ); }
动态转换(编译时类型未知)
1 2 3 4
Type enumType = ...; // 注意:枚举可以指定除 'int' 之外的基础类型 int numericValue = ...; object boxedEnumValue = Enum.ToObject(enumType, numericValue);