類似的東西可能工作:
private static IEnumerable<string> GetDescriptions(Type type)
{
var descs = new List<string>();
var names = Enum.GetNames(type);
foreach (var name in names)
{
var field = type.GetField(name);
var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
foreach (DescriptionAttribute fd in fds)
{
descs.Add(fd.Description);
}
}
return descs;
}
但是你可以查看一些邏輯存在:如是否確定要開始的名字?你將如何處理多個Description屬性?如果他們中的一些人失蹤了 - 你想要一個名字還是隻是像上面那樣跳過它?等
剛剛審查您的問題。對於VALUE你會有這樣的事情:
private static IEnumerable<string> GetDescriptions(Enum value)
{
var descs = new List<string>();
var type = value.GetType();
var name = Enum.GetName(type, value);
var field = type.GetField(name);
var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
foreach (DescriptionAttribute fd in fds)
{
descs.Add(fd.Description);
}
return descs;
}
但它是不可能將兩個說明單字段屬性,所以我想它可能會返回字符串只。
嗨,那些似乎不是我的問題的答案。我需要列出所有基礎枚舉值。我可以得到一個單獨的枚舉的描述,或者如果我明確知道類型,而不是簡單地傳遞Enum值。 – kodikas
啊,我明白你的意思了。你不能調用不僅僅是在其他答案中的代碼,而是傳入你的value.GetType()類型? –