EnumBind.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. namespace VCommon.Reflection
  6. {
  7. public abstract class EnumBind<T, TBase>
  8. {
  9. public static IReadOnlyDictionary<T, Type> BindedTypes { get; }
  10. public static IReadOnlyDictionary<Type, T> InvertMap { get; }
  11. private static readonly HashSet<T> Fields;
  12. public static bool Contains(T value) => Fields.Contains(value);
  13. static EnumBind()
  14. {
  15. if (false == typeof(T).IsEnum) throw new VCommonException("Generic type argument must be Enum.");
  16. BindedTypes = typeof(T).GetFields().Where(p => p.FieldType == typeof(T))
  17. .ToDictionary(
  18. k => (T)k.GetRawConstantValue(),
  19. p => p.GetCustomAttributes(typeof(EnumBindAttribute))
  20. .OfType<EnumBindAttribute>()
  21. .Select(t => t.BindType)
  22. .Single(t => typeof(TBase).IsAssignableFrom(t))
  23. );
  24. InvertMap = BindedTypes.ToDictionary(p => p.Value, p => p.Key);
  25. Fields = new HashSet<T>(BindedTypes.Keys);
  26. }
  27. }
  28. }