Files
Fishing2/Assets/Scripts/Common/Services/Settings/Base/MultiOption.cs
2025-05-30 17:49:12 +08:00

85 lines
2.0 KiB
C#

using System;
using System.Collections.Generic;
namespace NBF.Setting
{
public interface IMultiOption : IOptionBase
{
List<string> GetOptionNames();
int GetIndex();
void SetIndex(int index);
string GetName();
}
public abstract class MultiOption<T> : OptionBase, IMultiOption
{
private int _index;
protected OptionTable<T> OptionTable = new OptionTable<T>();
/// <summary>
/// 默认值
/// </summary>
protected abstract T DefaultValue { get; }
protected override void OnLoad()
{
}
protected void AddOption(string name, T value)
{
OptionTable.Add(name, value);
}
public List<string> GetOptionNames() => OptionTable.GetNames();
public string GetName()
{
return OptionTable.GetName(_index);
}
public int GetIndex()
{
return _index;
}
public void SetIndex(int index)
{
_index = index;
}
protected void SelectOption(T value, int defaultIndex = 0)
{
SetIndex(TryGetIndex(value, out var index) ? index : defaultIndex);
}
protected void SelectOption(Predicate<T> predicate, int defaultIndex = 0)
{
SetIndex(TryGetIndex(predicate, out var index) ? index : defaultIndex);
}
protected bool TryGetIndex(T option, out int index)
{
return TryGetIndex(entry => entry.Equals(option), out index);
}
protected bool TryGetIndex(Predicate<T> predicate, out int index)
{
index = -1;
var entries = OptionTable.GetValues();
for (var i = 0; i < entries.Count; i++)
{
if (!predicate(entries[i])) continue;
index = i;
return true;
}
return false;
}
public T GetSelectedOption() => OptionTable.GetValue(_index);
}
}