我想编写一个扩展方法来获取StringLength属性的MaximumLength属性的值。
例如,我有一个班级:
public class Person
{
[StringLength(MaximumLength=1000)]
public string Name { get; set; }
}
我希望能够做到这一点:
Person person = new Person();
int maxLength = person.Name.GetMaxLength();
使用某种反射会有可能吗?
答案 0 :(得分:4)
如果您使用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
以外的内容。你并不具体,但这很容易改变。
答案 1 :(得分:0)
这可能不是最好的方法,但如果您不介意提供属性名称,您需要获取属性值,您可以使用类似
的内容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这样的函数可以很好地运作