我發現這個解決方案:讀取屬性通行證屬性名稱由lambda表達式值
public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
{
var attrType = typeof(T);
var property = instance.GetType().GetProperty(propertyName);
return (T)property .GetCustomAttributes(attrType, false).First();
}
代碼由How to retrieve Data Annotations from code
jgauffin我總是使用擴展這種方式:
foo.GetAttributeFrom<StringLengthAttribute>(nameof(Foo.Bar)).MaximumLength
有沒有辦法通過使用lambda來傳遞propertyName:
foo.GetAttributeFrom<StringLengthAttribute>(f => f.Bar).MaximumLength
預先感謝您!