MINVALUE和放大器;房产属性的MaxValue [英] MinValue & MaxValue attribute for properties

查看:167
本文介绍了MINVALUE和放大器;房产属性的MaxValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能使属性,它可以限制号码最小值或最大值。

Is it possible to make attribute which can limit minimum or maximum value of numbers.

例如:

[MinValue(1), MaxValue(50)]
public int Size { get; set; }

当我做尺寸= -3; 的价值尺寸必须在1

我在谷歌搜索,并不能找到一个例子有关此问题的,也许是因为它是不可能做?

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.

看看类型转换器的可能性。

这篇关于MINVALUE和放大器;房产属性的MaxValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆