[英]How can I extract the regular expression from a RegularExpressionAttribute?
我有一个像
public class Foo
{
[RegularExpression(@"([A-Za-z0-9\-_ ]+){1,100}")]
public string Bar { get; set; }
}
并且出于单元测试的目的,我希望能够提取出"@"([A-Za-z0-9\\-_ ]+){1,100}"
。
我知道这就像
string expr = typeof(Foo).GetProperty("Bar").....
但我不太了解如何完成。
var property = typeof(Foo).GetProperty("Bar");
var attribute = property.GetCustomAttribute<RegularExpressionAttribute>();
var expr = attribute?.Pattern;
还是单条语句:
var expr = typeof(Foo).GetProperty("Bar")
.GetCustomAttribute<RegularExpressionAttribute>()?.Pattern;
注意:我认为您不应该从属性属性中提取数据进行单元测试。 我要么将属性验证留给验收测试。 或使用诸如Validator类之类的东西在对象上实际运行验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.