从C#中的值解码位掩码

239*_*ilo 3 c# bitmask bit bitflags

我正在尝试解码位掩码

[Flags]
public enum Amenities
{
    BusinessCenter = 1,
    FitnessCenter = 2,
    HotTub = 4,
    InternetAccess = 8,
    KidsActivities = 16,
    Kitchen = 32,
    PetsAllowed = 64,
    Pool = 128,
    Restaurant = 256,
    Spa = 512,
    Whirlpool = 1024,
    Breakfast = 2048,
    Babysitting = 4096,
    Jacuzzi = 8192,
    Parking = 16384,
    RoomService = 32768,
    AccessibleTravel = 65536,
    AccessibleBathroom = 131072,
    RollShower = 262144,
    HandicappedParking = 524288,
    InRoomAccessibility = 1048576,
    AccessibilityDeaf = 2097152,
    BrailleSignage = 4194304,
    FreeAirportShuttle = 8388608,
    IndoorPool =  16777216,
    OutdoorPool = 33554432,
    ExtendedParking = 67108864,
    FreeParking = 134217728
}
Run Code Online (Sandbox Code Playgroud)

如何编写一个函数来解码像5722635这样的值,并返回5722635中编码的所有设施的列表.

结果应如下所示:

此酒店有以下设施:

  • 商业中心
  • 健身中心
  • 互联网
  • 可在现场使用Spa
  • 临时保姆
  • 停车处
  • 无障碍旅行之路
  • 无障碍浴室
  • 滚入式淋浴
  • 室内无障碍设施
  • 盲文或凸起的标牌

我一直在尝试这样的事情

public List<Amenities> Decode(long mask)
        {
            var list = new List<Amenities>();
            for (var index = 0; index < 16; index++)
            {
                var bit = 1 << index;
                if (0 != (bit & mask))
                {
                    list.Add(new Amenities(index));
                }
            }
            return list;
        }
Run Code Online (Sandbox Code Playgroud)

但无法让它发挥作用.任何关于如何使这项工作正常的建议将不胜感激.

小智 9

单线怎么样?

var mask = (Amenities)5722635;

var result =
    Enum.GetValues(typeof(Amenities))
        .Cast<Amenities>()
        .Where(value => mask.HasFlag(value))
        .ToList();
Run Code Online (Sandbox Code Playgroud)

您可以缓存结果Enum.GetValues(typeof(Amenities)).Cast<Amenities>()以提高性能.