For a class Foo
I need an int-like property SanityCheckPeriod
that allows only values between two limits (say 1 till 7).
What is an elegant way to implement this requirement - maybe with attributes in a declarative manner? (because I need that pattern multiple times and for expressiveness it would be great to see the limits directly attached to the property.
The idea would be something like this:
public class Foo
{
[RangeAttribute(min: 1, max: 7)]
public Period SanityCheckPeriod { get; }
...
}
public class Period
{
private int _days;
private int _max;
private int _min;
public int Days
{
get => _days;
private set
{
if (_min <= value)
throw new ArgumentExcpetion($"Period must be equal or larger than {_min} day(s).");
if (value <= _max)
throw new ArgumentExcpetion($"Period must be equal or smaller than {_max} days.");
_days = value;
}
}
public Period(int days)
{
// access the RangeAttribute here
// how to do?
// and set _min and _max
}
}
[AttributeUsage(AttributeTargets.Property)]
public class RangeAttribute : Attribute
{
public int Min { get; }
public int Max { get; }
public RangeAttribute(int min, int max)
{
Min = min;
Max = max;
}
}
Aucun commentaire:
Enregistrer un commentaire