可以在set中设置超出指定范围时抛出异常,这样在属性网格中录入非法值时就会出现错误提示:
public int MyProperty
{
get
{
return myProperty;
}
set
{
if (value > 100 || value < 0)
{
throw new ArgumentOutOfRangeException("MyProperty只能为0到100之间的整数。");
}
}
}
如果你的属性是和数据字段绑定并且用于mvc的显示,那么.net提供了一些常用类型的标准验证属性标签的映射,位于System.ComponentModel.DataAnnotations数据注解空间下。用法如下:
using System.ComponentModel.DataAnnotations;
namespace MvcDA {
[MetadataType(typeof(ProductMD))]
public partial class Product {
public class ProductMD {
[StringLength(50),Required]
public object Name { get; set; }
[StringLength(15)]
public object Color { get; set; }
[Range(0, 9999)]
public object Weight { get; set; }
// public object NoSuchProperty { get; set; }
}
}
}
attribute只能设置提示来防止超出范围, 至于设置中属性的取值范围,好象不行.
就算能行的话还是建议通过自己代码实现,封装毕竟不是万能的不是吗?
get 和 set 就可以胜任, 你为啥非用别的方法呢