refactor: converted vkeycode enum into a class

This commit is contained in:
Gerard Gascón 2024-04-17 18:01:33 +02:00
parent e3f6db7ae5
commit 68d3d8065e
19 changed files with 123 additions and 54 deletions

View file

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Extensions {
public abstract class SmartEnum<TEnum, TValue> where TEnum : SmartEnum<TEnum, TValue> {
private static readonly List<TEnum> _list = new();
// Despite analysis tool warnings, we want this static bool to be on this generic type (so that each TEnum has its own bool).
private static bool _invoked;
public static List<TEnum> List {
get {
if (!_invoked) {
_invoked = true;
// Force invocaiton/initialization by calling one of the derived members.
typeof(TEnum).GetProperties(BindingFlags.Public | BindingFlags.Static)
.FirstOrDefault(p => p.PropertyType == typeof(TEnum))?.GetValue(null, null);
}
return _list;
}
}
public string Name { get; }
public TValue Value { get; }
protected SmartEnum(string name, TValue value) {
Name = name;
Value = value;
TEnum item = this as TEnum;
List.Add(item);
}
public static TEnum FromName(string name) {
return List.Single(item => string.Equals(item.Name, name, StringComparison.OrdinalIgnoreCase));
}
public static TEnum FromValue(TValue value) {
// Can't use == to compare generics unless we constrain TValue to "class", which we don't want because then we couldn't use int.
return List.Single(item => EqualityComparer<TValue>.Default.Equals(item.Value, value));
}
public override string ToString() => $"{Name} ({Value})";
public static implicit operator TValue(SmartEnum<TEnum, TValue> key) => key.Value;
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d14368a1c4e54cfb9e201b2d9801b602
timeCreated: 1713368573