CSharp · Console
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public class Program
{
public static void Main()
{
var flags = EnumHelper.GetFlags(typeof(A), 3);
Console.WriteLine(string.Join(", ", flags));
}
}
[Flags]
enum A
{
First = 1, Second = 2
}
static class EnumHelper
{
public static IEnumerable<Enum> GetFlags(Type enumType, int value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(string.Empty, nameof(enumType));
var attribute = enumType.GetCustomAttribute<FlagsAttribute>();
if (attribute == null)
throw new ArgumentException(string.Empty, nameof(enumType));
var enumValue = (Enum) Enum.ToObject(enumType, value);
return from Enum enumVal in enumType.GetEnumValues()
where enumValue.HasFlag(enumVal)
select enumVal;
}
}