是否可以制作可以限制数字的最小值或最大值的属性.
Is it possible to make attribute which can limit minimum or maximum value of numbers.
例子:
[MinValue(1), MaxValue(50)]
public int Size { get; set; }
当我执行 Size = -3;
时,Size
的值必须为 1.
and when i do Size = -3;
value of Size
must be 1.
我在 Google 中搜索并找不到有关此行为的单个示例,可能是因为无法制作?
I searched in Google and can't find single example about this behavior, maybe because it is not possible to make?
我将在属性网格中使用这些属性,因此自动验证会很方便.
I'm gonna use these attributes in property grid therefore having automatic validation can be handy.
目前我这样的解决方法来限制最小值:
Currently I workaround like this to limit minimum value:
private int size;
[DefaultValue(8)]
public int Size
{
get
{
return size;
}
set
{
size = Math.Max(value, 1);
}
}
所以这就像 MinValue(1)
So this acts like MinValue(1)
虽然可以创建自定义属性,但属性只是它们注释的成员的元数据,不能改变其行为.
Although it is possible to create a custom attribute, attributes are just metadata for the member they annotate, and cannot change its behavior.
因此,您不会使用普通属性获得所需的行为.您需要一些东西来处理属性以执行所需的行为.
So, you won't get the behavior you want with a plain attribute. You need something to process the attributes in order to enact the desired behavior.
看看 TypeConverters 一个可能性.
这篇关于最小值属性的 MaxValue 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!