2012-05-07 2 views
0

내 소스 코드를 마르고 싶습니다. 이 기능 중 일부가 주로 한 줄로 다른 기능을 가지고 있다고 가정 해 봅시다. 어떻게 구현할 수 있습니까?다양한 매개 변수가있는 델리게이트 사용

public Result foo (int x, int y, int z){ 
    Log.Say("Foo started!");         <<< DIFFERENCE 
    DoSomeMagic(); 
    try { 
     result = controller.foo(x, y, z);     <<< DIFFERENCE 
    } catch (Exception){ 
     Log.Say("Something went terribly wrong"); 
    } 
    return result; 
} 


public Result bar (Person a, string whatever){ 
    Log.Say("Bar started!");         <<< DIFFERENCE 
    DoSomeMagic(); 
    try { 
     result = controller.bar(a, whatever);    <<< DIFFERENCE 
    } catch (Exception) { 
     Log.Say("Something went terribly wrong"); 
    } 
    return result; 
} 

그렇게 어렵지 않을 수 있습니다. 나는 지금까지 다양한 접근법에 너무 혼란 스럽다. 지금까지 나는 대리자, Func, 람다 식, 익명 함수를 사용하여 작업을 시도했지만 작동하도록 가져올 수 없습니다 (휴식 필요).

public Result foo (int x, int y, int z) { 
    return handler(delegate() { 
     controller.foo(x, y, z)); 
     doSomethingOther(); 
    }); 
} 

어떤 제안이 같은이 익명의 기능을 사용 할 수있을 정말 좋은 것 첨가로

public Result handler (Func callbackMethodWithArgs) { 
    Result result = null; 
    Log.Say(method + " started!"); 
    DoSomeMagic(); 
    try { 
     result = invoke(callbackMethodWithArgs) as Result; 
    } catch (Exception) { 
     Log.Say("Something went terribly wrong"); 
    } 
    return result; 
} 

public Result foo (int x, int y, int z) { 
    return handler(controller.foo(x, y, z)); 
} 

public Result bar (Person a, string whatever) { 
    return handler(controller.bar(a, whatever); 
} 

, ?? 감사! (비슷한 주제에 대해 많은 질문을 읽었지 만 그 문제를 해결할만한 것을 찾지 못했습니다. 아마도 중복이라고 생각합니다. 그렇다면 미안 해요)

답변

2

Func<Result>을 사용하면됩니다 : 호출 사이트에서

public Result handler (string name, Func<Result> method) { 
    Result result = null; 
    Log.Say(name + " started!"); 
    DoSomeMagic(); 
    try { 
     result = method(); 
    } catch (Exception) { 
     Log.Say("Something went terribly wrong"); 
    } 
    return result; 
} 

그리고이 대표로를 설정 :

public Result foo (int x, int y, int z) { 
    return handler("Foo",() => controller.foo(x, y, z)); 
} 

public Result bar (Person a, string whatever) { 
    return handler("Bar",() => controller.bar(a, whatever); 
} 

참고 : 당신이 .NET 2.0에 있다면 당신은 Func<_> 대리자를 만들 수 있습니다 수동으로 위의 코드를 사용하기 전에 :

public delegate TResult Func<TResult>(); 

예외적으로 이러한 방식으로 예외를 숨기는 것은 좋은 생각이 아닙니다. 당신은 예외를 로깅하고 예외를 로깅하고 그것을 재실행하고 호출 코드가 무엇을 할 것인지를 결정하게합니다. 유스 케이스에서는 작동하지만 일반적으로 빨간색 플래그입니다.

+0

나는 당신의 방법을 좋아한다. – ykatchou

+0

어떤 .NET 버전을 사용하고 계십니까? – yamen

+0

.NET 4를 사용하고 있습니다 –