refactor: converted vkeycode enum into a class
This commit is contained in:
parent
e3f6db7ae5
commit
68d3d8065e
19 changed files with 123 additions and 54 deletions
49
Assets/Scripts/Extensions/SmartEnum.cs
Normal file
49
Assets/Scripts/Extensions/SmartEnum.cs
Normal 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;
|
||||
}
|
||||
}
|
3
Assets/Scripts/Extensions/SmartEnum.cs.meta
Normal file
3
Assets/Scripts/Extensions/SmartEnum.cs.meta
Normal file
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: d14368a1c4e54cfb9e201b2d9801b602
|
||||
timeCreated: 1713368573
|
Loading…
Add table
Add a link
Reference in a new issue