【发布时间】:2018-01-07 15:19:24
【问题描述】:
我正在尝试创建一个扩展方法,它将返回一个 List<string>,其中包含所有 Description 属性,仅用于给定 [Flags] Enum 的设置值。
例如,假设我在 C# 代码中声明了以下枚举:
[Flags]
public enum Result
{
[Description("Value 1 with spaces")]
Value1 = 1,
[Description("Value 2 with spaces")]
Value2 = 2,
[Description("Value 3 with spaces")]
Value3 = 4,
[Description("Value 4 with spaces")]
Value4 = 8
}
然后将变量设置为:
Result y = Result.Value1 | Result.Value2 | Result.Value4;
所以,我要创建的调用是:
List<string> descriptions = y.GetDescriptions();
最终的结果是:
descriptions = { "Value 1 with spaces", "Value 2 with spaces", "Value 4 with spaces" };
我创建了一个扩展方法,用于为不能设置多个标志的枚举获取 单个描述属性,如下所示:
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
System.Reflection.FieldInfo field = type.GetField(name);
if (field != null)
{
DescriptionAttribute attr =
Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
}
我在网上找到了一些关于如何获取给定枚举类型(例如here)的所有描述属性的答案,但是我在编写通用扩展方法以返回描述列表时遇到问题仅用于设置的属性。
任何帮助将不胜感激。
谢谢!!
【问题讨论】:
-
我编辑了你的标题,因为当你使用 C#时你的问题不是about C#(你的标题中没有必要有标签,除非它是它的一个组成部分)
-
@slugster,我把它放在我的标题中,因为我想提到它是 ac# 问题而不是 Java / 其他语言 - 我正在寻找一种用特定语言编写的扩展方法,所以我觉得合适。
标签: c# reflection enums system.componentmodel