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

Say*_*emi 2 c# enums enum-flags

萨拉姆.我有这个标志枚举:

public enum DataAccessPoliceis
{
      None = 0,
      A = 1,
      B = 2,
      C = 4, 
      D = 8, 
      E = B | C | D, // 14
      All = A | E // 15
}
Run Code Online (Sandbox Code Playgroud)

我想从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 }
Run Code Online (Sandbox Code Playgroud)

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

dya*_*nko 6

使用可以使用类EnumGetValues方法.尝试它像这样:

var lstEnumValues = new List<int>(Enum.GetValues(typeof(DataAccessPolicies)).Cast<int>());
Run Code Online (Sandbox Code Playgroud)

输出是:

输出结果

希望这可以帮助.

  • @SayedAbolfazlFatemi - 这个答案为你做了很多事.你只需要在演员表之后添加一个`.Where(x => x!= 0 &&(x&15)== x)`. (2认同)

Say*_*emi 5

我的问题的答案:

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

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