using System;
using System.ComponentModel;
using System.Reflection;
public static class EnumHelper
{
// 一个泛型方法,接受一个泛型类型T和一个字符串s作为参数
public static T GetEnumByDescription<T>(string s) where T : Enum
{
// 获取T的所有枚举值
var values = Enum.GetValues(typeof(T));
// 遍历每个枚举值
foreach (var value in values)
{
// 获取枚举值的Description特性,如果有的话
var field = value.GetType().GetField(value.ToString());
var attribute = field.GetCustomAttribute<DescriptionAttribute>();
// 如果Description特性的值和字符串s匹配,就返回对应的枚举值
if (attribute != null && attribute.Description == s)
{
return (T)value;
}
}
// 如果没有匹配的枚举值,就抛出异常
throw new ArgumentException("No matching enum value found.");
}
}