Building class is used as a more flexible alternative to Enum (Type safe enum pattern).
I would like to be able to view the available static fields in runtime.
In my solution, each such class will have to uniformly implement the static GetAllFields () method, which I don’t really like.
Is there a more elegant solution to this problem than mine?
public abstract class ABase { protected static IEnumerable<ABase> GetAllField(Type type) { var res = from x in type.GetFields() where x.IsStatic == true where x.IsPublic == true select x.GetValue(null); ABase obj; foreach(var item in res) { if(!(item is ABase)) continue; obj = item as ABase; yield return obj; } } } public sealed class Building : ABase { public static readonly Building House = new Building(); public static readonly Building Castle = new Building(); public static System.Collections.Generic.IEnumerable<ABase> GetAllFields() { return GetAllField(typeof(Building)); } }
protected
then the conditionif(!(item is ABase))
will never be fulfilled. It is alwaysfalse
- Anton Komyshan