[.NET]根据某个数值,获取Flags枚举所代表的所有值

public static IEnumerable<T> GetEnumValuesFromFlagsEnum<T>(Int32 value) where T : struct
        {
            T[] values = (T[])Enum.GetValues(typeof(T));

            foreach (var itemValue in values)
            {
                if((value & Convert.ToInt32(itemValue)) != 0)
                {
                    yield return itemValue;
                }
            }
        }


测试


[TestMethod]
        public void GetEnumValuesFromFlagsEnumTestHelper()
        {
            var foods  = EnumHelper.GetEnumValuesFromFlagsEnum<Foods>(9);
            Assert.AreEqual(2,foods.Count());
            Assert.IsTrue(foods.Contains(Foods.主食));
            Assert.IsTrue(foods.Contains(Foods.菜3));
            foreach (var food in foods)
            {
                Console.WriteLine(food);
            }
        }

 [Flags]
 public enum Foods
 {
        主食=1,
        菜1 = 2,
        菜2 = 4,
        菜3=8,
        菜4 = 16
 }


你可能感兴趣的:(.net)