确定Enum-flag组合中包含的标志数量的最佳做法?

Ele*_*ios 4 .net c# vb.net enums enum-flags

在某些情况下,当我将Enum传递给方法时,我需要处理它是否是单个Enum值,否则它是一个标志组合,为此我编写了这个简单的扩展:

Vb.Net:

<Extension>
Public Function FlagCount(ByVal sender As System.[Enum]) As Integer
    Return sender.ToString().Split(","c).Count()
End Function
Run Code Online (Sandbox Code Playgroud)

C#(在线翻译):

[Extension()]
public int FlagCount(this System.Enum sender) {
    return sender.ToString().Split(',').Count();
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

Vb.Net:

Dim flags As FileAttributes = (FileAttributes.Archive Or FileAttributes.Compressed)
Dim count As Integer = flags.FlagCount()
MessageBox.Show(flagCount.ToString())
Run Code Online (Sandbox Code Playgroud)

C#(在线翻译):

FileAttributes flags = (FileAttributes.Archive | FileAttributes.Compressed);
int count = flags.FlagCount();
MessageBox.Show(flagCount.ToString());
Run Code Online (Sandbox Code Playgroud)

我只是想问一下,如果存在一种更直接,更有效的方式,我现在正在做的是避免将标志组合表示为String然后拆分它.

Avi*_*ner 6

选项A:

public int FlagCount(System.Enum sender)
{
    bool hasFlagAttribute = sender.GetType().GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0;
    if (!hasFlagAttribute) // No flag attribute. This is a single value.
        return 1;

    var resultString = Convert.ToString(Convert.ToInt32(sender), 2);
    var count = resultString.Count(b=> b == '1');//each "1" represents an enum flag.
    return count;
}
Run Code Online (Sandbox Code Playgroud)

说明:

  • 如果枚举没有"标志属性",则它必然是单个值.
  • 如果枚举具有"标志属性",则将其转换为位表示并计算"1".每个"1"代表一个枚举标志.

选项B:

  1. 获取所有flaged项目.
  2. 算他们......

代码:

public int FlagCount(this System.Enum sender)
{
  return sender.GetFlaggedValues().Count;
}

/// <summary>
/// All of the values of enumeration that are represented by specified value.
/// If it is not a flag, the value will be the only value returned
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public static List<Enum> GetFlaggedValues(this Enum value)
{
    //checking if this string is a flagged Enum
    Type enumType = value.GetType();
    object[] attributes = enumType.GetCustomAttributes(true);

    bool hasFlags = enumType.GetCustomAttributes(true).Any(attr => attr is System.FlagsAttribute);
    //If it is a flag, add all flagged values
    List<Enum> values = new List<Enum>();
    if (hasFlags)
    {
        Array allValues = Enum.GetValues(enumType);
        foreach (Enum currValue in allValues)
        {
            if (value.HasFlag(currValue))
            {
                values.Add(currValue);
            }
        }
    }
    else//if not just add current value
    {
        values.Add(value);
    }
    return values;
}
Run Code Online (Sandbox Code Playgroud)