简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM