【问题标题】:How can I extract the regular expression from a RegularExpressionAttribute?如何从 RegularExpressionAttribute 中提取正则表达式?
【发布时间】:2017-07-06 06:23:53
【问题描述】:

我有这样的课

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").....

但我不知道如何完成它。

【问题讨论】:

    标签: c# .net unit-testing reflection custom-attributes


    【解决方案1】:
    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 的类来实际对您的对象运行验证。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多