我们在Student中实现如下方法:
public bool Validate(){
bool result = true;
Type type = this.GetType();
PropertyInfo property = type.GetProperty(“Source”); //获取Source属性
RangeAttribute [] attributes =
property.GetCustomAttributes(typeof(Attribute), true)
as RangeAttribute []; //获取Range属性集合
//遍历集合对属性进行验证
foreach(var item in attribute){
int value = (int)property.GetValue(this, null);
if(value < item.Min || value > item.Max){
result = false;
}
}
return result;
}
bool result = true;
Type type = this.GetType();
PropertyInfo property = type.GetProperty(“Source”); //获取Source属性
RangeAttribute [] attributes =
property.GetCustomAttributes(typeof(Attribute), true)
as RangeAttribute []; //获取Range属性集合
//遍历集合对属性进行验证
foreach(var item in attribute){
int value = (int)property.GetValue(this, null);
if(value < item.Min || value > item.Max){
result = false;
}
}
return result;
}
那么再回过头看先前的测试,我们可以发现,测试成功运行了(相关代码见附带项目的Leven.Validate01和test项目Validate01Test.cs).
我们在看目前的代码,现在我们能测试Source,如果我们的Student类中还有一项Age,范围为6-150呢,那么Student中加上如下代码:
[Range(6, 150, "学生年龄必须在{0}和{1}之间.")]
public int Age { get; set; }
public int Age { get; set; }
那么我们的Validate方法是否能正确验证呢?为了验证结果,我们重新编写测试:
[TestMethod()]
public void ValidateTest() {
Student student = new Student() {
Source = 80,
Age = 0
};
bool validateResult = student.Validate();
Assert.IsFalse(validateResult);
student.
validateResult = student.Validate();
}
public void ValidateTest() {
Student student = new Student() {
Source = 80,
Age = 0
};
bool validateResult = student.Validate();
Assert.IsFalse(validateResult);
student.
validateResult = student.Validate();
}
执行测试,很遗憾,测试无法通过了.我们可以再看看Validate方法,可以发现,其中只对Source属性进行了验证,那么我们可以想办法修改代码,让其能对Age和Source方法同时验证.
public bool Validate() {
bool result = true;
Type type = this.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (var property in properties) {
RangeAttribute[] attributes =
property.GetCustomAttributes(typeof(RangeAttribute), true) as RangeAttribute[];
foreach (var item in attributes) {
int value = (int)property.GetValue(this, null);
if (value < item.Min || value > item.Max) {
result = false;
}
}
}
return result;
}
bool result = true;
Type type = this.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (var property in properties) {
RangeAttribute[] attributes =
property.GetCustomAttributes(typeof(RangeAttribute), true) as RangeAttribute[];
foreach (var item in attributes) {
int value = (int)property.GetValue(this, null);
if (value < item.Min || value > item.Max) {
result = false;
}
}
}
return result;
}
修改过的方法中将遍历所有的属性,然后进行验证,这时候再次运行测试,生动的绿色代表我们重新获得了成功.