[英]How can I extract the regular expression from a RegularExpressionAttribute?
I have a class like 我有一个像
public class Foo
{
[RegularExpression(@"([A-Za-z0-9\-_ ]+){1,100}")]
public string Bar { get; set; }
}
and for the purpose of unit testing I want to be able to extract out the "@"([A-Za-z0-9\\-_ ]+){1,100}"
. 并且出于单元测试的目的,我希望能够提取出"@"([A-Za-z0-9\\-_ ]+){1,100}"
。
I know it's something like 我知道这就像
string expr = typeof(Foo).GetProperty("Bar").....
but I don't quite know how to finish it. 但我不太了解如何完成。
var property = typeof(Foo).GetProperty("Bar");
var attribute = property.GetCustomAttribute<RegularExpressionAttribute>();
var expr = attribute?.Pattern;
Or single statement: 还是单条语句:
var expr = typeof(Foo).GetProperty("Bar")
.GetCustomAttribute<RegularExpressionAttribute>()?.Pattern;
NOTE: I don't think that you should extract data from property attributes for unit testing. 注意:我认为您不应该从属性属性中提取数据进行单元测试。 I would either leave property validation for acceptance tests. 我要么将属性验证留给验收测试。 Or used something like Validator class to actually run validation on your object. 或使用诸如Validator类之类的东西在对象上实际运行验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.