从标记的枚举中获取描述属性

问题描述 投票:4回答:3

我正在尝试创建一个扩展方法,它将返回包含所有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" };

我已经创建了一个扩展方法,用于获取Enum的单个描述属性,该属性不能设置多个标记,这些标记位于以下行中:

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# reflection enums system.componentmodel
3个回答
8
投票

HasFlag是你的朋友。 :-)

下面的扩展方法使用您在上面发布的GetDescription扩展方法,因此请确保您拥有该方法。然后应该有以下工作:

public static List<string> GetDescriptionsAsText(this Enum yourEnum)
{       
    List<string> descriptions = new List<string>();

    foreach (Enum enumValue in Enum.GetValues(yourEnum.GetType()))
    {
        if (yourEnum.HasFlag(enumValue))
        {
            descriptions.Add(enumValue.GetDescription());
        }
    }

    return descriptions;
}

注意:HasFlag允许您将给定的Enum值与定义的标志进行比较。在你的例子中,如果你有

Result y = Result.Value1 | Result.Value2 | Result.Value4;

然后

y.HasFlag(Result.Value1)

应该是真的,而

y.HasFlag(Result.Value3)

将是假的。

另见:https://msdn.microsoft.com/en-us/library/system.enum.hasflag(v=vs.110).aspx


2
投票

这是一个使用LINQ的紧凑解决方案,如果并非所有值都具有属性,它也会检查null

public static List<T> GetFlagEnumAttributes<T>(this Enum flagEnum) where T : Attribute
{
   var type = flagEnum.GetType();
   return Enum.GetValues(type)
      .Cast<Enum>()
      .Where(flagEnum.HasFlag)
      .Select(e => type.GetMember(e.ToString()).First())
      .Select(info => info.GetCustomAttribute<T>())
      .Where(attribute => attribute != null)
      .ToList();
}

0
投票

您可以从枚举中迭代所有值,然后过滤未包含在输入值中的值。

    public static List<T> GetAttributesByFlags<T>(this Enum arg) where T: Attribute
    {
        var type = arg.GetType();
        var result = new List<T>();
        foreach (var item in Enum.GetValues(type))
        {
            var value = (Enum)item;
            if (arg.HasFlag(value)) // it means that '(arg & value) == value'
            {
                var memInfo = type.GetMember(value.ToString())[0];
                result.Add((T)memInfo.GetCustomAttribute(typeof(T), false));
            }
        }
        return result;
    }

并获得所需的属性列表:

var arg = Result.Value1 | Result.Value4;
List<DescriptionAttribute> attributes = arg.GetAttributesByFlags<DescriptionAttribute>();
© www.soinside.com 2019 - 2024. All rights reserved.