In .Net it is possible to iterate through an enumeration by using
System.Enum.GetNames(typeof(MyEnum))
or
System.Enum.GetValues(typeof(MyEnum))
In Silverlight 3 however, Enum.GetNames and Enum.GetValues are not defined. Does anyone know an alternative?
To iterate through an enumeration, you can move it into an array using the GetValues method. You could also iterate through an enumeration using a For... Each statement, using the GetNames or GetValues method to extract the string or numeric value.
Roughly, yes. There are two kind of reflection code, the general kind that goes through RuntimeType and the specific kind that uses dedicated CLR helper functions. The latter uses type info that can retrieved from the internal type representation that the CLR maintains. The fast kind.
Or maybe strongly typed using linq, like this:
public static T[] GetEnumValues<T>() { 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<T>() { 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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With