Iterating through an enumeration in Silverlight?

前端 未结 4 1963
孤街浪徒
孤街浪徒 2020-12-03 16:53

In .Net it is possible to iterate through an enumeration by using

System.Enum.GetNames(typeof(MyEnum)) 

or

System.Enum.Ge         


        
4条回答
  •  执念已碎
    2020-12-03 17:34

    Or maybe strongly typed using linq, like this:

        public static T[] GetEnumValues()
        {
            var type = typeof(T);
            if (!type.IsEnum)
                throw new ArgumentException("Type '" + type.Name + "' is not an enum");
    
            return (
              from field in type.GetFields(BindingFlags.Public | BindingFlags.Static)
              where field.IsLiteral
              select (T)field.GetValue(null)
            ).ToArray();
        }
    
        public static string[] GetEnumStrings()
        {
            var type = typeof(T);
            if (!type.IsEnum)
                throw new ArgumentException("Type '" + type.Name + "' is not an enum");
    
            return (
              from field in type.GetFields(BindingFlags.Public | BindingFlags.Static)
              where field.IsLiteral
              select field.Name
            ).ToArray();
        }
    

提交回复
热议问题