일반적인 방법이를 달성하기 위해,이 같은 EndInvoke
을 무시 확장 메서드를 선언해야 할 것 :
public static class DelegateExtensions
{
public static TResult EndInvoke<TDelegate, TResult>(this TDelegate asyncCaller, IAsyncResult asyncResult) where TDelegate : System.Delegate
{
TResult result = default(TResult);
try
{
result = asyncCaller.EndInvoke(asyncResult);
}
catch (Exception ex)
{
LogExceptionMessageOrWhatever(ex.Message);
throw;
}
return result;
}
}
그러나, 그 절차는 컴파일러 오류가 발생합니다. 왜? System.Delegate
클래스는 제네릭 제약 조건에서 사용할 수없는 특수 클래스입니다.
제약 조건을 제거하고 리플렉션을 사용하여 올바른 절차를 호출 할 수는 없습니까?
당신은 할 수 있다고 생각하지만, 제네릭 사용의 목적을 상실합니다. 더 나은 해결책은 당신의 델리게이트를 generic으로 만든 다음 그 델리게이트 만 대상으로 확장 메소드를 다시 작성하는 것입니다.
public delegate TFooResult GetFooAsync<TFooResult>();
public static class GetFooAsyncExtensions
{
public static TFooResult EndInvoke<TFooResult>(this GetFooAsync<TFooResult> asyncCaller, IAsyncResult asyncResult)
{
TFooResult result = default(TFooResult);
try
{
result = asyncCaller.EndInvoke(asyncResult);
}
catch (Exception ex)
{
LogExceptionMessageOrWhatever(ex.Message);
throw;
}
return result;
}
}
이제 평소와 같이 EndInvoke
을 부르면됩니다. 프레임 워크는 자동으로 귀하의 버전을 사용합니다.
private void Main()
{
Foo1Result foo1 = null;
var foo1Factory = new GetFooAsync<Foo1Result>(
() =>
{
return new Foo1Result();
});
foo1Factory.BeginInvoke(
callback: asyncResult =>
{
foo1 = foo1Factory.EndInvoke(asyncResult);
},
@object: null);
}
이 두 biltin delegeates는 .NET Func을에 있고 액션 당신은 람다 식을 전달할 수는 90 %의 시나리오 –
Developerzzz
를 덮고 사용 http://stackoverflow.com/questions/14297633/c-sharp- pass-lambda-expression-as-method-parameter –
대리자를 매개 변수로 사용하는 대리자를 작성하는 이유를 이해할 수 없습니다. 이런 종류의 중첩이없는 솔루션을 작성했습니다. 도움이되지 않으면 예제를 실제 코드로 바꿉니다. –