在C#中将int转换为枚举
时间:2020-03-05 18:43:38 来源:igfitidea点击:
如何将int转换为C#中的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);
回答
请看以下示例:
int one = 1; MyEnum e = (MyEnum)one;
回答
只需将其转换为:
MyEnum e = (MyEnum)3;
我们可以使用Enum.IsDefined检查它是否在范围内:
if (Enum.IsDefined(typeof(MyEnum), 3)) { ... }
回答
有时我们有一个MyEnum类型的对象。喜欢
var MyEnumType = typeof(MyEnumType);
然后:
Enum.ToObject(typeof(MyEnum), 3)
回答
下面是一个不错的Enums实用程序类
public static class EnumHelper { public static int[] ToIntArray<T>(T[] value) { int[] result = new int[value.Length]; for (int i = 0; i < value.Length; i++) result[i] = Convert.ToInt32(value[i]); return result; } public static T[] FromIntArray<T>(int[] value) { T[] result = new T[value.Length]; for (int i = 0; i < value.Length; i++) result[i] = (T)Enum.ToObject(typeof(T),value[i]); return result; } internal static T Parse<T>(string value, T defaultValue) { if (Enum.IsDefined(typeof(T), value)) return (T) Enum.Parse(typeof (T), value); int num; if(int.TryParse(value,out num)) { if (Enum.IsDefined(typeof(T), num)) return (T)Enum.ToObject(typeof(T), num); } return defaultValue; } }