2017-03-18 61 views
2

我發現這個解決方案:讀取屬性通行證屬性名稱由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 

預先感謝您!

回答

2

可以以繞過指定爲一個通用的方法中的所有通用參數類型限制

public static object[] GetPropertyAttributes<TObject, TProperty>(
    this TObject instance, 
    Expression<Func<TObject, TProperty>> propertySelector) 
{ 
    //consider handling exceptions and corner cases 
    var propertyName = ((PropertyInfo)((MemberExpression)propertySelector.Body).Member).Name; 
    var property = instance.GetType().GetProperty(propertyName); 
    return property.GetCustomAttributes(false); 
} 

public static T GetFirst<T>(this object[] input) where T : Attribute 
{ 
    //consider handling exceptions and corner cases 
    return input.OfType<T>().First(); 
} 

然後用它像

foo.GetPropertyAttributes(f => f.Bar) 
    .GetFirst<StringLengthAttribute>() 
    .MaximumLength; 
0

方法可以是分裂工作成兩個函數像這樣:

public static TAtt GetAttribute<TAtt,TObj,TProperty>(this Rootobject inst, 
    Expression<Func<TObj,TProperty>> propertyExpression) 
     where TAtt : Attribute 
     { 
     var body = propertyExpression.Body as MemberExpression; 
     var expression = body.Member as PropertyInfo; 
     var ret = (TAtt)expression.GetCustomAttributes(typeof(TAtt), false).First(); 

     return ret; 
     } 

I F你有這樣的類屬性:

public class Rootobject 
{ 
    [StringLengthAttribute(10)] 
    public string Name { get; set; } 
} 

這時你會使用這樣的:

var obj = new Rootobject(); 
     var max = obj.GetAttribute<StringLengthAttribute, Rootobject, string>((x) => x.Name) 
         .MaximumLength; 

改進

添加錯誤的情況下,檢查屬性未找到或者拉姆達不適用於財產等。