public static T ToEnum<T>(this string value){return (T) Enum.Parse(typeof(T), value, true);}
StatusEnum MyStatus = "Active".ToEnum<StatusEnum>();
最后,如果无法解析字符串,您可能希望使用默认枚举:
public static T ToEnum<T>(this string value, T defaultValue){if (string.IsNullOrEmpty(value)){return defaultValue;}
T result;return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;}
public static TEnum ParseEnum<TEnum>(string value) where TEnum : struct{TEnum tmp;if (!Enum.TryParse<TEnum>(value, true, out tmp)){tmp = new TEnum();}return tmp;}
public static T ParseEnum<T>(string value, T defaultValue) where T : struct{try{T enumValue;if (!Enum.TryParse(value, true, out enumValue)){return defaultValue;}return enumValue;}catch (Exception){return defaultValue;}}
public static T ParseEnum<T>(string value) //function declaration{return (T) Enum.Parse(typeof(T), value);}
Importance imp = EnumUtil.ParseEnum<Importance>("Active"); //function call
====================一个完整的程序====================
using System;
class Program{enum PetType{None,Cat = 1,Dog = 2}
static void Main(){
// Possible user input:string value = "Dog";
// Try to convert the string to an enum:PetType pet = (PetType)Enum.Parse(typeof(PetType), value);
// See if the conversion succeeded:if (pet == PetType.Dog){Console.WriteLine("Equals dog.");}}}-------------Output
Equals dog.
namespace System{public static class StringExtensions{
public static bool TryParseAsEnum<T>(this string value, out T output) where T : struct{T result;
var isEnum = Enum.TryParse(value, out result);
output = isEnum ? result : default(T);
return isEnum;}}}
下面是我的实现与测试。
using static Microsoft.VisualStudio.TestTools.UnitTesting.Assert;using static System.Console;
private enum Countries{NorthAmerica,Europe,Rusia,Brasil,China,Asia,Australia}
[TestMethod]public void StringExtensions_On_TryParseAsEnum(){var countryName = "Rusia";
Countries country;var isCountry = countryName.TryParseAsEnum(out country);
WriteLine(country);
IsTrue(isCountry);AreEqual(Countries.Rusia, country);
countryName = "Don't exist";
isCountry = countryName.TryParseAsEnum(out country);
WriteLine(country);
IsFalse(isCountry);AreEqual(Countries.NorthAmerica, country); // the 1rst one in the enumeration}
public static bool TryParse<T>(string value, out T result)where T : struct{var cacheKey = "Enum_" + typeof(T).FullName;
// [Use MemoryCache to retrieve or create&store a dictionary for this enum, permanently or temporarily.// [Implementation off-topic.]var enumDictionary = CacheHelper.GetCacheItem(cacheKey, CreateEnumDictionary<T>, EnumCacheExpiration);
return enumDictionary.TryGetValue(value.Trim(), out result);}
private static Dictionary<string, T> CreateEnumDictionary<T>(){return Enum.GetValues(typeof(T)).Cast<T>().ToDictionary(value => value.ToString(), value => value, StringComparer.OrdinalIgnoreCase);}
<Extension()>Public Function ToEnum(Of TEnum)(ByVal value As String, ByVal defaultValue As TEnum) As TEnumIf String.IsNullOrEmpty(value) ThenReturn defaultValueEnd If
Return [Enum].Parse(GetType(TEnum), value, True)End Function
public static T ParseEnum<T>(this string s, T defaultValue, bool ignoreCase = false)where T : struct, IComparable, IConvertible, IFormattable//If C# >=7.3: struct, System.Enum{if ((s?.Length ?? 0) == 0){return defaultValue;}
var valid = Enum.TryParse<T>(s, ignoreCase, out T res);
if (!valid || !Enum.IsDefined(typeof(T), res)){throw new InvalidOperationException($"'{s}' is not a valid value of enum '{typeof(T).FullName}'!");}return res;}