我想要一个简单的方法来确保某个类中的某些属性包含值和/或在一个范围内(即:不超过50个字符长)。我在How to validate Class properties?上使用了问题和答案,不幸的是我无法使其工作。如何验证类属性中的必填字段?
为了测试它,我使用C#创建了一个非常简单的WinForm示例。尽管我做的都是一样的,但是当我使用不正确的值时(即:将年龄设置为高于允许的限制),它从不会引发验证异常。
有人可以解释为什么它不抛出异常?就好像类不知道它应该使用所需的属性。
Form1.cs的
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.ComponentModel.DataAnnotations;
namespace RequiredFieldsInClassExample {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void btnTest_Click(object sender, EventArgs e) {
try {
lstStatus.Items.Clear();
lstStatus.Items.Add("Creating list of people");
List<Person> CollectionOfPeople = new List<Person>();
lstStatus.Items.Add("Creating a good person");
Person Jeff = new Person();
Jeff.Age = 33;
Jeff.Firstname = "Jeff";
Jeff.Lastname = "Jefferson";
Jeff.GroupCode = "JJJ";
CollectionOfPeople.Add(Jeff);
lstStatus.Items.Add("Creating a bad person");
Person Tim = new Person();
Tim.Age = 444;
Tim.Firstname = "";
Tim.Lastname = "";
Tim.GroupCode = "";
CollectionOfPeople.Add(Tim);
lstStatus.Items.Add("Done");
} catch (ValidationException Exp) {
MessageBox.Show(this, Exp.Message, "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
} catch (Exception Exp) {
MessageBox.Show(this, Exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
}
Person.cs
using System.ComponentModel.DataAnnotations;
public class Person {
private int m_iAge = 1;
private string m_sFirstname = "Unknown";
private string m_sLastname = "";
private string m_sGroupCode = "AAA";
//[Required(ErrorMessage = "Age is a required field.")]
//[Range(1, 100, ErrorMessage = "A persons age must be between 1 and 100.")]
[Required, Range(1, 100)]
public int Age
{
get { return m_iAge; }
set { m_iAge = value; }
}
//[Required(ErrorMessage = "Firstname is a required field.")]
[Required]
public string Firstname
{
get { return m_sFirstname; }
set { m_sFirstname = value; }
}
public string Lastname
{
get { return m_sLastname; }
set { m_sLastname = value; }
}
//[StringLength(3)]
public string GroupCode
{
get { return m_sGroupCode; }
set { m_sGroupCode = value; }
}
}
它不会在设定值来验证属性,你必须[触发手动验证(http://odetocode.com/blogs/scott/archive/2011/ 06/29 /手动验证与 - 数据annotations.aspx)。 – Michael
@Michael - 你能否创建一个答案,因为你的链接包含了允许我解决问题的信息? – ThePeter
如果没有其他答案,您也可以发布自己的答案,并在延迟后自行接受答案。这将标志着问题的答案,这将有助于未来的读者。 – Tim