获取 StringLength 值的扩展方法

And*_*rew 1 c# reflection attributes

我想编写一个扩展方法来获取 StringLength 属性上的 MaximumLength 属性的值。

例如,我有一个类:

public class Person
{
    [StringLength(MaximumLength=1000)]
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我希望能够做到这一点:

Person person = new Person();
int maxLength = person.Name.GetMaxLength();
Run Code Online (Sandbox Code Playgroud)

使用某种反射可以实现吗?

Chr*_*air 5

如果您使用 LINQ 表达式,您可以通过反射以略有不同的语法提取信息(并且您可以避免在常用string类型上定义扩展方法):

public class StringLength : Attribute
{
    public int MaximumLength;

    public static int Get<TProperty>(Expression<Func<TProperty>> propertyLambda)
    {
        MemberExpression member = propertyLambda.Body as MemberExpression;
        if (member == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a method, not a property.",
                propertyLambda.ToString()));

        PropertyInfo propInfo = member.Member as PropertyInfo;
        if (propInfo == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a field, not a property.",
                propertyLambda.ToString()));

        var stringLengthAttributes = propInfo.GetCustomAttributes(typeof(StringLength), true);
        if (stringLengthAttributes.Length > 0)
            return ((StringLength)stringLengthAttributes[0]).MaximumLength;

        return -1;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以你的Person班级可能是:

public class Person
{
    [StringLength(MaximumLength=1000)]
    public string Name { get; set; }

    public string OtherName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

您的用法可能如下所示:

Person person = new Person();

int maxLength = StringLength.Get(() => person.Name);
Console.WriteLine(maxLength); //1000

maxLength = StringLength.Get(() => person.OtherName);
Console.WriteLine(maxLength); //-1
Run Code Online (Sandbox Code Playgroud)

除了-1没有定义该属性的属性之外,您还可以返回其他内容。你不是特定的,但这很容易改变。