2013-11-21 26 views
3

我想從類型枚舉變量的所有枚舉值都枚舉常量:更好的方式來獲得合併枚舉值

[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()));   

} 

有沒有更好的方式來做到這一點?

+2

回答時:http://stackoverflow.com/questions/4171140/iterate-over-values-in-flags-enum – 2013-11-21 09:25:34

回答

6
List<Type> types = Enum 
        .GetValues(typeof(Type)) 
        .Cast<Type>() 
        .Where(val => (val & type) == val) 
        .ToList(); 

獲得所需結果的另一種方式。

-1

首先儘量不要使用單詞「類型」命名enum.Use EnumType或別的東西,使用Enum.GetValues..something這樣

public static List<EnumType> GetValues(Type enumType) 
    { 
     List<EnumType > enums = new List<EnumType >(); 
     if (!enumType.IsEnum) throw new ArgumentException(Enum type not found"); 

     foreach (EnumType value in Enum.GetValues(enumType)) 
      enums.Add(value); 

     return enums; 
    } 
+0

這不是我真正要求的 –