mirror of
https://github.com/Cysharp/R3.git
synced 2026-10-18 14:41:14 +08:00
86 lines
2.2 KiB
C#
86 lines
2.2 KiB
C#
using R3;
|
|
using System.ComponentModel.DataAnnotations;
|
|
using System.Runtime.CompilerServices;
|
|
using System.Runtime.InteropServices;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using System.Text.Json.Serialization.Metadata;
|
|
|
|
// CollectionsMarshal.GetValueRef
|
|
var v = new ClampedReactiveProperty2<int>(5, 10, 30);
|
|
|
|
Console.WriteLine(v.Value);
|
|
|
|
|
|
public sealed class ClampedReactiveProperty<T>(T initialValue, T min, T max)
|
|
: ReactiveProperty<T>(initialValue) where T : IComparable<T>
|
|
{
|
|
private static IComparer<T> Comparer { get; } = Comparer<T>.Default;
|
|
|
|
protected override void OnValueChanging(ref T value)
|
|
{
|
|
if (Comparer.Compare(value, min) < 0)
|
|
{
|
|
value = min;
|
|
}
|
|
else if (Comparer.Compare(value, max) > 0)
|
|
{
|
|
value = max;
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
public sealed class ClampedReactiveProperty2<T>
|
|
: ReactiveProperty<T> where T : IComparable<T>
|
|
{
|
|
private static IComparer<T> Comparer { get; } = Comparer<T>.Default;
|
|
|
|
readonly T min, max;
|
|
|
|
// callOnValueChangeInBaseConstructor to avoid OnValueChanging call before min, max set.
|
|
public ClampedReactiveProperty2(T initialValue, T min, T max)
|
|
: base(initialValue, EqualityComparer<T>.Default, callOnValueChangeInBaseConstructor: false)
|
|
{
|
|
this.min = min;
|
|
this.max = max;
|
|
|
|
// modify currentValue manually
|
|
OnValueChanging(ref GetValueRef());
|
|
}
|
|
|
|
protected override void OnValueChanging(ref T value)
|
|
{
|
|
if (Comparer.Compare(value, min) < 0)
|
|
{
|
|
value = min;
|
|
}
|
|
else if (Comparer.Compare(value, max) > 0)
|
|
{
|
|
value = max;
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
//[JsonConverter(typeof(IgnoreCaseStringReactivePropertyJsonConverter))]
|
|
public class IgnoreCaseStringReactiveProperty : ReactiveProperty<string>
|
|
{
|
|
public IgnoreCaseStringReactiveProperty(string value)
|
|
: base(value, StringComparer.OrdinalIgnoreCase)
|
|
{
|
|
|
|
}
|
|
}
|
|
|
|
internal class IgnoreCaseStringReactivePropertyJsonConverter : ReactivePropertyJsonConverter<string>
|
|
{
|
|
protected override ReactiveProperty<string> CreateReactiveProperty(string value)
|
|
{
|
|
return new IgnoreCaseStringReactiveProperty(value);
|
|
}
|
|
}
|