我想编写一个扩展方法来获取 StringLength 属性的 MaximumLength 属性的值。
比如我有一个类:
public class Person
{
[StringLength(MaximumLength=1000)]
public string Name { get; set; }
}
我希望能够做到这一点:
Person person = new Person();
int maxLength = person.Name.GetMaxLength();
这是否可以使用某种反射来实现?
请您参考如下方法:
如果您使用 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 以外的内容。您没有具体说明,但这很容易更改。
