我正在尝试创建一个扩展方法,该方法将返回一个仅包含给定的设置值的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;
}
而且我在网上找到了一些关于如何获取给定 Enum 类型的所有 Description 属性的答案(例如这里),但是我在编写通用扩展方法以仅返回 set attributes的描述列表时遇到问题。
任何帮助将非常感激。
谢谢!!