我试图创建一个扩展方法,该方法将返回包含所有Description
属性的List<string>
属性,仅用于给定的[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;
}
而且我已经找到了一些答案在线如何获取给定枚举类型的所有Description属性(例如here),但是我在编写通用扩展方法时遇到问题,仅返回的描述列表,仅用于设置属性。
任何帮助将非常感激。
谢谢!
我编辑您的标题,因为当你*使用* C#你的问题不是*约* C#(这是没有必要使标签你的标题,除非它是它的一个组成部分) – slugster
@slugster,我把它放在我的标题中,因为我想提到它是ac#问题而不是Java /某些其他语言 - 我正在寻找一种扩展方法语言,所以我认为它是适当的。 –