2017-01-23 5 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

당신은 다음을 수행 할 수 있습니다 : 당신이 Func<T, R> 더 의미가 없기 때문에 다른 void 방법을 처리 할 필요가

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; 
} 

주, 당신은 Action<T>에 과부하가 필요합니다.

+0

고맙습니다! –

+0

@ 한스 다비 당신은 매우 환영합니다! – InBetween

관련 문제