我正在尝试从Type枚举变量中获取所有枚举值:
[Flags]
enum Type
{
XML = 1,
HTML = 2,
JSON = 4,
CVS = 8
}
static void Main(string[] args)
{
Type type = Type.JSON | Type.XML;
List<Type> types = new List<Type>();
foreach (string elem in type.ToString().Split(',') )
types.Add( (Type)Enum.Parse( typeof(Type), elem.Trim() ) );
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?
List<Type> types = Enum
.GetValues(typeof(Type))
.Cast<Type>()
.Where(val => (val & type) == val)
.ToList();
Run Code Online (Sandbox Code Playgroud)
获得理想结果的另一种方式