2017-01-23 96 views
7

下面我有一個解決方案來從具有擴展方法的字段中獲取屬性。現在我想用方法而不是字段來做類似的事情。使用擴展方法在方法上訪問屬性

public static MemberInfo GetMember<T, R>(this T instance, Expression<Func<T, R>> selector) 
{ 
    var member = selector.Body as MemberExpression; 
    return member?.Member; 
} 

public static T GetAttribute<T>(this MemberInfo meminfo) where T : Attribute 
{ 
    return meminfo.GetCustomAttributes(typeof(T)).FirstOrDefault() as T; 
} 

用法:

var attr = this.GetMember(x => x.AddButtonVisibility).GetAttribute<Test>(); 

所以在我的情況下使用應該是這個樣子:

var attr = this.GetMethod(x => x.SomeMethod).GetAttribute<Test>(); 

這是可能以任何方式或我必須嘗試一些完全不同的?

+0

您是否收到任何錯誤?目前還不清楚你在問什麼。同樣適用於MethodInfo – Nkosi

+0

@Nkosi沒有上面的代碼工作,但我想用方法而不是字段做同樣的事情。 –

回答

6

你可以做到以下幾點:

public static MethodInfo GetMethod<T>(this T instance, Expression<Action<T>> selector) 
{ 
    var member = selector.Body as MethodCallExpression; 
    return member?.Method; 
} 

public static MethodInfo GetMethod<T, R>(this T instance, Expression<Func<T, R>> selector) 
{ 
    var member = selector.Body as MethodCallExpression; 
    return member?.Method; 
} 

請注意,你需要不同的處理方法void因爲Func<T, R>是沒有意義的,你需要Action<T>過載。

+0

謝謝你這工作! –

+0

@HansDabi非常歡迎你! – InBetween