有很多的例子中,你可以通過自定義獲取枚舉屬性喜歡這裏 Get Enum from Description attribute獲取枚舉通過自定義屬性(通用)
public static class EnumEx
{
public static T GetValueFromDescription<T>(string description)
{
var type = typeof(T);
if(!type.IsEnum) throw new InvalidOperationException();
foreach(var field in type.GetFields())
{
var attribute = Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) as DescriptionAttribute;
if(attribute != null)
{
if(attribute.Description == description)
return (T)field.GetValue(null);
}
else
{
if(field.Name == description)
return (T)field.GetValue(null);
}
}
throw new ArgumentException("Not found.", "description");
// or return default(T);
}
}
但這裏的問題是,你有硬編碼的屬性類型,即typeof(DescriptionAttribute)) as DescriptionAttribute
如何將此示例轉換爲通用擴展,以便我不必硬編碼CustomAttributeType。
作爲一種理念,你可以添加一個泛型參數的方法,但你應該知道的輸入參數的含義和用法能夠使用它進行搜索。例如,現在你可以使用這個標準if(attribute.Description == description)'但是當你傳遞一個泛型參數時呢? –
那你怎麼翻譯這個:'attribute.Description'如果'attribute'不是'DescriptionAttribute'? – HimBromBeere