YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);
// The foo.ToString().Contains(",") check is necessary for// enumerations marked with a [Flags] attribute.if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(",")){throw new InvalidOperationException($"{yourString} is not an underlying value of the YourEnum enumeration.");}
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;}}
for (var flagIterator = 0; flagIterator < 32; flagIterator++){// Determine the bit value (1,2,4,...,Int32.MinValue)int bitValue = 1 << flagIterator;
// Check to see if the current flag exists in the bit maskif ((intValue & bitValue) != 0){// If the current flag exists in the enumeration, then we can add that value to the list// if the enumeration has that flag definedif (Enum.IsDefined(typeof(MyEnum), bitValue))Console.WriteLine((MyEnum)bitValue);}}
public static class EnumEx{static public bool TryConvert<T>(int value, out T result){result = default(T);bool success = Enum.IsDefined(typeof(T), value);if (success){result = (T)Enum.ToObject(typeof(T), value);}return success;}}
.class public auto ansi serializable sealed BarFlag extends System.Enum{.custom instance void System.FlagsAttribute::.ctor().custom instance void ComVisibleAttribute::.ctor(bool) = { bool(true) }
.field public static literal valuetype BarFlag AllFlags = int32(0x3fff).field public static literal valuetype BarFlag Foo1 = int32(1).field public static literal valuetype BarFlag Foo2 = int32(0x2000)
// and so on for all flags or enum values
.field public specialname rtspecialname int32 value__}
public enum MyEnum : short{Mek = 5}
static void Main(string[] args){var e1 = (MyEnum)32769; // will not compile, out of bounds for a short
object o = 5;var e2 = (MyEnum)o; // will throw at runtime, because o is of type int
Console.WriteLine("{0} {1}", e1, e2);Console.ReadLine();}
[DataContract]public class EnumMember{[DataMember]public string Description { get; set; }
[DataMember]public int Value { get; set; }
public static List<EnumMember> ConvertToList<T>(){Type type = typeof(T);
if (!type.IsEnum){throw new ArgumentException("T must be of type enumeration.");}
var members = new List<EnumMember>();
foreach (string item in System.Enum.GetNames(type)){var enumType = System.Enum.Parse(type, item);
members.Add(new EnumMember() { Description = enumType.GetDescriptionValue(), Value = ((IConvertible)enumType).ToInt32(null) });}
return members;}}
这是从枚举中获取描述的扩展方法。
public static string GetDescriptionValue<T>(this T source){FieldInfo fileInfo = source.GetType().GetField(source.ToString());DescriptionAttribute[] attributes = (DescriptionAttribute[])fileInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0){return attributes[0].Description;}else{return source.ToString();}}
public static class Question{public static readonly int Role = 2;public static readonly int ProjectFunding = 3;public static readonly int TotalEmployee = 4;public static readonly int NumberOfServers = 5;public static readonly int TopBusinessConcern = 6;}
这将整数或字符串解析为目标枚举,并在. NET 4.0中使用Tawani的实用程序中的泛型进行部分匹配。我使用它来转换可能不完整的命令行开关变量。由于枚举不能为空,您应该在逻辑上提供一个默认值。它可以像这样调用:
var result = EnumParser<MyEnum>.Parse(valueToParse, MyEnum.FirstValue);
以下是代码:
using System;
public class EnumParser<T> where T : struct{public static T Parse(int toParse, T defaultVal){return Parse(toParse + "", defaultVal);}public static T Parse(string toParse, T defaultVal){T enumVal = defaultVal;if (defaultVal is Enum && !String.IsNullOrEmpty(toParse)){int index;if (int.TryParse(toParse, out index)){Enum.TryParse(index + "", out enumVal);}else{if (!Enum.TryParse<T>(toParse + "", true, out enumVal)){MatchPartialName(toParse, ref enumVal);}}}return enumVal;}
public static void MatchPartialName(string toParse, ref T enumVal){foreach (string member in enumVal.GetType().GetEnumNames()){if (member.ToLower().Contains(toParse.ToLower())){if (Enum.TryParse<T>(member + "", out enumVal)){break;}}}}}
public class Program{public enum Color : int{Blue = 0,Black = 1,Green = 2,Gray = 3,Yellow = 4}
public static void Main(string[] args){// From stringConsole.WriteLine((Color) Enum.Parse(typeof(Color), "Green"));
// From intConsole.WriteLine((Color)2);
// From number you can alsoConsole.WriteLine((Color)Enum.ToObject(typeof(Color), 2));}}
public static TEnum ToEnum<TEnum>(this int val) where TEnum : struct, IComparable, IFormattable, IConvertible{if (!typeof(TEnum).IsEnum){return default(TEnum);}
if (Enum.IsDefined(typeof(TEnum), val)){//if a straightforward single value, return thatreturn (TEnum)Enum.ToObject(typeof(TEnum), val);}
var candidates = Enum.GetValues(typeof(TEnum)).Cast<int>().ToList();
var isBitwise = candidates.Select((n, i) => {if (i < 2) return n == 0 || n == 1;return n / 2 == candidates[i - 1];}).All(y => y);
var maxPossible = candidates.Sum();
if (Enum.TryParse(val.ToString(), out TEnum asEnum)&& (val <= maxPossible || !isBitwise)){//if it can be parsed as a bitwise enum with multiple flags,//or is not bitwise, return the result of TryParsereturn asEnum;}
//If the value is higher than all possible combinations,//remove the high imaginary values not accounted for in the enumvar excess = Enumerable.Range(0, 32).Select(n => (int)Math.Pow(2, n)).Where(n => n <= val && n > 0 && !candidates.Contains(n)).Sum();
return Enum.TryParse((val - excess).ToString(), out asEnum) ? asEnum : default(TEnum);}
public static T ToEnum<T>(dynamic value){if (value == null){// default value of an enum is the object that corresponds to// the default value of its underlying type// https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/default-values-tablevalue = Activator.CreateInstance(Enum.GetUnderlyingType(typeof(T)));}else if (value is string name){return (T)Enum.Parse(typeof(T), name);}
return (T)Enum.ToObject(typeof(T),Convert.ChangeType(value, Enum.GetUnderlyingType(typeof(T))));}
测试用例
[Flags]public enum A : uint{None = 0,X = 1 < 0,Y = 1 < 1}
static void Main(string[] args){var value = EnumHelper.ToEnum<A>(7m);var x = value.HasFlag(A.X); // truevar y = value.HasFlag(A.Y); // true
var value2 = EnumHelper.ToEnum<A>("X");
var value3 = EnumHelper.ToEnum<A>(null);
Console.ReadKey();}
public static class Extensions{
public static T ToEnum<T>(this string data) where T : struct{if (!Enum.TryParse(data, true, out T enumVariable)){if (Enum.IsDefined(typeof(T), enumVariable)){return enumVariable;}}
return default;}
public static T ToEnum<T>(this int data) where T : struct{return (T)Enum.ToObject(typeof(T), data);}}
YourEnum possibleEnum = (YourEnum)value; // There isn't any guarantee that it is part of the enumif (Enum.IsDefined(typeof(YourEnum), possibleEnum)){// Value exists in YourEnum}