1

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

例如,我有一堂课:

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

我希望能够做到这一点:

Person person = new Person();
int maxLength = person.Name.GetMaxLength();

这可以使用某种反射吗?

4

2 回答 2

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;
    }
}

所以你的Person班级可能是:

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

    public string OtherName { get; set; }
}

您的用法可能如下所示:

Person person = new Person();

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

maxLength = StringLength.Get(() => person.OtherName);
Console.WriteLine(maxLength); //-1

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

于 2013-07-10T01:34:22.323 回答
1

这可能不是最好的方法,但如果您不介意提供属性名称,您需要获取属性值,您可以使用类似

public static class StringExtensions
{
    public static int GetMaxLength<T>(this T obj, string propertyName) where T : class
    {
        if (obj != null)
        {
            var attrib = (StringLengthAttribute)obj.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance)
                    .GetCustomAttribute(typeof(StringLengthAttribute), false);
            if (attrib != null)
            {
                return attrib.MaximumLength;
            }
        }
        return -1;
    }
}

用法:

Person person = new Person();
int maxLength = person.GetMaxLength("Name");

否则,使用他的评论中提到的像 Chris Sinclair 这样的函数会很好地工作

于 2013-07-10T01:35:03.200 回答