注意:这是对previous question上的answer的后续操作。使用反射通过从设置者调用的方法获取属性的属性
我正在用一个名为TestMaxStringLength
的属性装饰一个属性的setter,该属性在setter调用的方法中用于验证。
该物业目前看起来是这样的:
public string CompanyName
{
get
{
return this._CompanyName;
}
[TestMaxStringLength(50)]
set
{
this.ValidateProperty(value);
this._CompanyName = value;
}
}
但我宁愿它是这样的:
[TestMaxStringLength(50)]
public string CompanyName
{
get
{
return this._CompanyName;
}
set
{
this.ValidateProperty(value);
this._CompanyName = value;
}
}
为ValidateProperty
的代码,负责查找的属性设置器:
private void ValidateProperty(string value)
{
var attributes =
new StackTrace()
.GetFrame(1)
.GetMethod()
.GetCustomAttributes(typeof(TestMaxStringLength), true);
//Use the attributes to check the length, throw an exception, etc.
}
如何更改ValidateProperty
代码寻找属性属性而不是设置方法?
哦。从编码的角度来看,我更喜欢这种方法。当然,除非实现验证,否则属性修饰是无用的,在这个模型中稍微难以假设,但总体而言,它应该更快更干净。 – 2010-09-02 16:41:19
你能告诉我如何验证这个值与atts的对应关系吗?谢谢! – VladL 2013-11-06 15:40:34