用于获取StringLength值的扩展方法

本文关键字:扩展 方法 获取 StringLength 用于 | 更新日期: 2023-09-27 18:21:55

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

例如,我有一个类:

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

我希望能够做到这一点:

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

这可能通过某种反射实现吗?

用于获取StringLength值的扩展方法

如果使用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以外的其他内容。你没有具体说明,但这很容易改变。

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

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在评论中提到的函数会很好地工作