![](/img/trans.png)
[英]How to specify a min but no max decimal using the range data annotation attribute?
[英]How can I get and set the Range attribute min and max?
[Range(-3, 3)]
public float range;
我希望稍后在代码中执行以下操作:
range.min = 2
range.max = 20;
或者得到
int min = range.min;
int max = range.max;
您不能在运行时更改属性的 state ,但您可以使用反射读取它:
class YourClass
{
[Range(-3, 3)]
public float range;
}
var range = typeof(YourClass)
.GetField(nameof(YourClass.range))
.GetCustomAttribute<RangeAttribute>();
float min = range.min;
float max = range.max;
您可以将其更改为如下所示的 object 吗?
public class range
{
private float _value;
public range(int min, int max)
{
Min = min;
Max = max;
}
public float Value
{
get
{
return _value;
}
set
{
if (value > Max || value < Min) throw new Exception("value out of
range.");
_value = value;
}
}
public int Min { get; }
public int Max { get; }
}
像这样使用它;
rangeObj = new range(-3,3);
rangeObj.Min
rangeObj.Max
rangeObj.Value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.