AcceptableValueList.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Linq;
  3. namespace BepInEx.Configuration
  4. {
  5. /// <summary>
  6. /// Specify the list of acceptable values for a setting.
  7. /// </summary>
  8. public sealed class AcceptableValueList<T> : AcceptableValueBase where T : IEquatable<T>
  9. {
  10. private readonly T[] _acceptableValues;
  11. /// <summary>
  12. /// Specify the list of acceptable values for a setting.
  13. /// If the setting does not equal any of the values, it will be set to the first one.
  14. /// </summary>
  15. public AcceptableValueList(params T[] acceptableValues) : base(typeof(T))
  16. {
  17. if (acceptableValues == null) throw new ArgumentNullException(nameof(acceptableValues));
  18. if (acceptableValues.Length == 0) throw new ArgumentException("At least one acceptable value is needed", nameof(acceptableValues));
  19. _acceptableValues = acceptableValues;
  20. }
  21. /// <inheritdoc />
  22. public override object Clamp(object value)
  23. {
  24. if (IsValid(value))
  25. return value;
  26. return _acceptableValues[0];
  27. }
  28. /// <inheritdoc />
  29. public override bool IsValid(object value)
  30. {
  31. return value is T v && _acceptableValues.Any(x => x.Equals(v));
  32. }
  33. /// <inheritdoc />
  34. public override string ToSerializedString()
  35. {
  36. return "# Acceptable values: " + string.Join(", ", _acceptableValues.Select(x => x.ToString()).ToArray());
  37. }
  38. }
  39. }