C#에서 랩핑 된 메소드 속성에 액세스
-
20-09-2019 - |
문제
다음 코드가 있습니다.
public static void ProcessStep(Action action)
{
//do something here
if (Attribute.IsDefined(action.Method, typeof(LogAttribute)))
{
//do something here [1]
}
action();
//do something here
}
쉽게 사용하기 위해 위의 방법을 사용하여 비슷한 방법이 있습니다. 예를 들어:
public static void ProcessStep(Action<bool> action)
{
ProcessStep(() => action(true)); //this is only example, don't bother about hardcoded true
}
그러나 두 번째 방법 (위의 방법)을 사용하면 원래 조치에 속성이 있더라도 코드 [1]은 실행되지 않습니다.
메소드가 래퍼와 기본 메소드가 속성을 포함 하고이 속성에 액세스하는 방법이 포함되어 있는지 어떻게 알 수 있습니까?
해결책
표현 나무를 사용할 수 있다고 확신하지만 가장 쉬운 솔루션은 MethodInfo 유형의 추가 매개 변수를 사용하는 오버로드를 작성하고 다음과 같이 사용하는 것입니다.
public static void ProcessStep(Action<bool> action)
{
ProcessStep(() => action(true), action.Method); //this is only example, don't bother about hardcoded true
}
다른 팁
글쎄, 당신은 할 수 있습니다 (반드시 이것이 좋은 코드라고 생각하지는 않습니다 ...)
void ProcessStep<T>(T delegateParam, params object[] parameters) where T : class {
if (!(delegateParam is Delegate)) throw new ArgumentException();
var del = delegateParam as Delegate;
// use del.Method here to check the original method
if (Attribute.IsDefined(del.Method, typeof(LogAttribute)))
{
//do something here [1]
}
del.DynamicInvoke(parameters);
}
ProcessStep<Action<bool>>(action, true);
ProcessStep<Action<string, string>>(action, "Foo", "Bar")
그러나 그것은 당신에게 미인 대회를 이기지 못할 것입니다.
당신이 무엇을하려고하는지에 대한 더 많은 정보를 줄 수 있다면 유용한 조언을 줄 수있는 것이 더 쉬울 것입니다 ... (이 페이지의 솔루션이 정말 귀엽지 않기 때문에)
제휴하지 않습니다 StackOverflow