我有这样的课:public class Animal{ [Required] [StringLength(20)] public string Name { get; set; } public double Weight { get; set; } public double Height { get; set; } public int AnimalID { get; set; }}我必须使用它生成 XML,但在此之前,我必须检查这些数据的正确性(例如Weight,不能超过 100,AnimalID应该在 0 到 9 的范围内)。我该怎么做?
1 回答

慕娘9325324
TA贡献1783条经验 获得超4个赞
您可以使用DataAnnotations从DataAnnotations命名空间。这样,您可以将对象包装在如下所示的 try/catch 块中并捕获 ValidationExceptions:
try {
Animal animal = GetAnimal();
}catch(ValidationException ex)
{}
public class Animal
{
[Required]
[StringLength(20)]
public string Name { get; set; }
[Required, RangeAttribute(0,100)]
public double Weight { get; set; }
public double Height { get; set; }
[Required, RangeAttribute(0, 9)]
public int AnimalID { get; set; }
}
此外,如果您使用的是 MVC,那么您可以使用 ModelState.IsValid 等方法。
- 1 回答
- 0 关注
- 113 浏览
添加回答
举报
0/150
提交
取消