如果使用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
以外的內容。你並不具體,但很容易改變。
我想你也許可以做一個LINQ表達的東西用類似用法:'INT最大長度=海峽ingLength.Get(()=> person.Name);'編輯:這是我正在談論的基本概念;不同的用法,但想法是傳遞一個lambda表達式並利用LINQ'Expression'對象來檢查引用的屬性並檢索它的屬性:http://stackoverflow.com/questions/671968/retrieving-property-name-from -lambda-expression –