I am trying to implement an enumeration class found at https://github.com/jbogard/presentations/blob/master/WickedDomainModels/After/Model/Enumeration.cs.
In the following code, I am getting a compile error that GetFields
cannot be resolved.
public static IEnumerable<T> GetAll<T>() where T : Enumeration
{
var type = typeof(T);
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
return fields.Select(info => info.GetValue(null)).OfType<T>();
}
According to http://msdn.microsoft.com/en-us/library/ch9714z3(v=vs.110).aspx, this method is supported in Portable Class Libraries.
My library is targeting .NET for Windows Store apps, .NET Framework 4.5 and Windows Phone 8.
Any idea of what is going on here?
public static IEnumerable<T> GetAll<T>() where T : Enumeration
{
var type = typeof(T);
var fields = type.GetRuntimeFields().Where(x => x.IsPublic || x.IsStatic);
return fields.Select(info => info.GetValue(null)).OfType<T>();
}
public static IEnumerable GetAll(Type type)
{
var fields = type.GetRuntimeFields().Where(x => x.IsPublic || x.IsStatic);
return fields.Select(info => info.GetValue(null));
}
To add to Damien's answer, in .Net for Windows Store Apps, you can use the following extension method:
using System.Reflection;
var fields = type.GetRuntimeFields();
This seems to be the equivalent of the GetFields
method for the .Net Framework.
This method returns all fields that are defined on the specified type, including inherited, non-public, instance, and static fields.