繁体   English   中英

如何将 int 值转换为列出 Flag 枚举的 int 值

[英]How to cast int value to list int value of Flag enums

我有这个标志枚举:

public enum DataAccessPoliceis
{
      None = 0,
      A = 1,
      B = 2,
      C = 4, 
      D = 8, 
      E = B | C | D, // 14
      All = A | E // 15
}

我想从 int 值中获取 int 值(或复杂枚举项的 int 值列表):

int x = 9; // enum items => D | A
List<int> lstEnumValues = ???
// after this line ...
// lstEnumValues = { 1, 8 }
// and for x = 15
// lstEnumValues = { 1, 2, 4, 8, 14, 15 }

你对这个问题的解决方案是什么?

使用可以使用类EnumGetValues方法。 试试这样:

var lstEnumValues = new List<int>(Enum.GetValues(typeof(DataAccessPolicies)).Cast<int>());

输出是:

输出结果

希望这可以帮助。

回答我的问题:

var lstEnumValues = new List<int>Enum.GetValues(typeof(DataAccessPoliceis)).Cast<int>())
.Where(enumValue => enumValue != 0 && (enumValue & x) == enumValue).ToList();

@dyatchenko 和 @Enigmativity 感谢您的回复。

尝试:

var lstEnumValues =
    ((DataAccessPoliceis[])(Enum.GetValues(typeof(DataAccessPoliceis))))
    .Where(v => v.HasFlag(x))
    .Select(v => (int)v)  // omit if enum values are OK
    .ToList();            // omit if List<> not needed

对于这些场景,我更喜欢使用扩展方法。

public static IEnumerable<Enum> ToEnumerable(this Enum input)
{
    foreach (Enum value in Enum.GetValues(input.GetType()))
        if (input.HasFlag(value) && Convert.ToInt64(value) != 0)
            yield return value;
}

用法:

 var lstEnumValues = flagEnum.ToEnumerable().Select(x => Convert.ToInt32(x)).ToList();  

还有一种方法:

由于标志只是以 2 为底的取幂数的组合,并且每个自然数在二进制数系统中都只有一种表示形式,因此实际上只考虑二进制表示形式(而不是枚举本身)就足够了。 转换为二进制表示后,只需将所有带“1”的位置转换回十进制(并省略零)并以列表形式输出。

在 LINQ 的帮助下,可以这样写:

int value = 9;

//convert int into a string of the the binary representation
string binary = Convert.ToString(value, 2);

var listOfInts = binary

    //convert each binary digit back to a decimal
    .Select((v, i) => Int32.Parse(v.ToString()) * Math.Pow(2, binary.Length-i-1))   
    
    //filter decimal numbers that are based on the "1" in binary representation
    .Where(x => x > 0)  

     //you want the integers in ascending order
    .OrderBy(x => x);   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM