using System; using System.Collections.Generic; using System.Linq; using UnityEngine.Assertions; namespace RosettaUI { public static class EnumToIdxBinder { public static IBinder Create(IBinder binder) { var valueType = binder.ValueType; var binderType = typeof(EnumToIdxBinder<>).MakeGenericType(valueType); return Activator.CreateInstance(binderType, binder) as IBinder; } } public class EnumToIdxBinder : ConvertBinder { public EnumToIdxBinder(IBinder parentBinder) : base(parentBinder) { } protected override int GetFromParent(TFrom parent) => ToIdxFunc(parent); protected override TFrom SetToParent(TFrom parent, int value) => ToEnumFunc(parent, value); #region static static readonly Func ToIdxFunc; static readonly Func ToEnumFunc; static EnumToIdxBinder() { Assert.IsTrue(typeof(TFrom).IsEnum); var idxToValue = Enum.GetValues(typeof(TFrom)).Cast().ToList(); var valueToIdx = new Dictionary(); for(var i=0; i { valueToIdx.TryGetValue(e, out var ret); return ret; }; ToEnumFunc = (e, idx) => { return (0 <= idx && idx < idxToValue.Count) ? idxToValue[idx] : e; }; } #endregion } }