Last active
February 16, 2018 20:23
-
-
Save Fusion86/9dbeb113dac40c5894987113b50a4b32 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Reflection; | |
namespace Ayra.Core.Enums | |
{ | |
// Based on https://lostechies.com/jimmybogard/2008/08/12/enumeration-classes/ | |
public abstract class Enumeration : IComparable | |
{ | |
public readonly int Id; | |
public readonly string Name; | |
public Enumeration() { } | |
protected Enumeration(int id, string name) | |
{ | |
Id = id; | |
Name = name; | |
} | |
public override int GetHashCode() | |
{ | |
return Id.GetHashCode(); | |
} | |
public override string ToString() | |
{ | |
return Name; | |
} | |
public static IEnumerable<T> GetAll<T>() where T : Enumeration, new() | |
{ | |
var type = typeof(T); | |
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly); | |
foreach (var info in fields) | |
{ | |
var instance = new T(); | |
if (info.GetValue(instance) is T locatedValue) | |
{ | |
yield return locatedValue; | |
} | |
} | |
} | |
public int CompareTo(object obj) | |
{ | |
return Id.CompareTo(((Enumeration)obj).Id); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment