Created
July 30, 2023 18:36
-
-
Save 0xF6/188e0d03c77a4bf405204e4424ef2f58 to your computer and use it in GitHub Desktop.
EnumCache Class with MaxValue\MinValue underlying number
This file contains 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
public static class EnumCache<T> | |
{ | |
public class Cache<X> | |
{ | |
public Array Values { get; } | |
public object[] UnderlyingValues { get; } | |
public int TotalValues { get; } | |
public Type UnderlyingType { get; } | |
public Type SelfType => typeof(X); | |
public long MaxValue => | |
this.UnderlyingValues.Select(x => (long)Convert.ChangeType(x, typeof(long))).Max(x => x); | |
public long MinValue => | |
this.UnderlyingValues.Select(x => (long)Convert.ChangeType(x, typeof(long))).Min(x => x); | |
public ulong UnsignedMaxValue => | |
this.UnderlyingValues.Select(x => (ulong)Convert.ChangeType(x, typeof(ulong))).Max(x => x); | |
public ulong UnsignedMinValue => | |
this.UnderlyingValues.Select(x => (ulong)Convert.ChangeType(x, typeof(ulong))).Min(x => x); | |
public Cache() | |
{ | |
this.Values = Enum.GetValues(typeof(X)); | |
this.TotalValues = Enum.GetValues(typeof(X)).Length; | |
this.UnderlyingType = Enum.GetUnderlyingType(typeof(X)); | |
this.UnderlyingValues = Enumerable.Range(0, this.TotalValues).Select(x => this.Values.GetValue(x)) | |
.Select(x => Convert.ChangeType(x, this.UnderlyingType)).ToArray(); | |
} | |
} | |
private static Cache<T> _cache; | |
public static Cache<T> Value => _cache ??= new Cache<T>(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment