求教,有关C#读取对象属性的方法
大家好,我最近在写一个验证代码语句是RuleFor.(s=>s.Name).NotEmpty()
然后我要写对这个验证语句的一个测试代码,我想直接使用属性的名称,再调用这个验证语句
我已经试过s.GetType().getProperties("name").GetValue(s,null)
但是会报异常
求救各位了!
--------------------编程问答-------------------- 什么验证代码? --------------------编程问答-------------------- 用fluentvalidation,做验证 --------------------编程问答-------------------- 报错看看你查找的属性在不在,注意大小写 --------------------编程问答-------------------- 没有报错,是出一场,好像是有关LinQ的异常 --------------------编程问答-------------------- 请LZ贴出你的异常~ --------------------编程问答-------------------- 代码:
对象:
namespace model
{
public class Model
{
public Guid Id { get; set; }
public bool checkout { get; set; }
public string name { get; set; }
public string fortest { get; set; }
}
}
验证:
namespace modelValidator
{
public class modelValidatorTT:AbstractValidator<Model>
{
public modelValidatorTT()
{
RuleFor(s =>s.name).NotEmpty();
}
}
}
对验证的测试:
namespace modelValicateT
{
[TestFixture]
public class testValidator
{
private modelValidatorTT validator=new modelValidatorTT();
[Test]
public void Should_have_error_when_name_is_null()
{
Model m1 = new Model();
m1.name = "123";
Type t = m1.GetType();
PropertyInfo pi = t.GetProperties()[2];
object o = pi.GetValue(m1, null);
validator.ShouldNotHaveValidationErrorFor(s => (string)s.GetType().GetProperties()[2].GetValue(s, null), null as string);
}
}
}
运行测试,报异常
modelValicateT.testValidator.Should_have_error_when_name_is_null:
System.NullReferenceException : Object reference not set to an instance of an object.
谢谢大家了
补充:.NET技术 , C#