2010-12-03 5 views
0

이 질문은 이전에 다른 방법으로 요청되었지만 응답이 도움이되지 않습니다. 왜냐하면 (1) 내장 된 Exception 클래스를 제어 할 수 없기 때문에 2) Activator.CreateInstance()은 진정한 동적 유형이 필요한 객체/인스턴스를 반환합니다.동적 제네릭 형식을 요구하는 예외 확장 메서드

내가 잡는 예외를 기반으로 FaultException을 내 WCF 서비스 밖으로 던질 수있는 확장 메서드를 만들려고합니다. 예 :

try { 
    ... 
} 
catch (ArgumentNullException exc) { 
    throw new FaultException<ArgumentNullException>(exc); 
} 

은 간단합니다.

public static void ThrowFaultException(this Exception exc) { 

    // Gives me the correct type... 
    Type exceptionType = exc.GetType(); 

    // But how the heck do I use it? 
    throw new FaultException<???>(exc); 
} 
:

나는 물론, 너무 신경
try { 
    ... 
} 
catch (Exception exc) { 
    exc.ThrowFaultException(); 
} 

은 확장 메서드의 구현 : 나는 일반적인 방법으로이를 확장 할 경우, 나는 같은 확장 클래스를 사용하는 것

대답은 herehere는 도움이되지 않습니다. 어떤 아이디어?

+0

왜 수 있습니다 ' 'Activator.CreateInstance()'에서 'Exception'으로 반환 값을 던지겠습니까? 그것은 여전히 ​​실제 유형으로 던져 질 것입니까? –

+0

일반화 된 메서드가 아닌 사용자 지정 코드에서 예외를 throw하는 것이 좋습니다. 그러면 VS.Net 및 다른 코드 분석기 (동료 포함)가 도달 할 수없는 코드 및 관련 문제를 감지하는 데 도움이됩니다. –

+0

BR/DP> 호출자가 FaultException

답변

3

이 시도 :

public static void ThrowFaultException<TException>(this TException ex) where TException : System.Exception 
{ 
    throw new FaultException<TException>(ex); 
} 
+0

완벽하게 작동한다 !! 정확히 원했던 것 :) –

+0

나는 제네릭의 아름다움을 끊임없이 잊어 버린다! –

1

Activator.CreateInstance에서 반환 한 객체를 FaultException으로 형 변환 할 필요가 없습니다. <? > 던지십시오. 예외에 주조 충분하다 :

var type = typeof(FaultException<>).MakeGenericType(exc.GetType()); 

throw (Exception)Activator.CreateInstance(type, exc); 

내가 생각 ThrowFaultException에서 예외를 던질 것입니다 :

try 
{ 
    ... 
} 
catch (Exception e) 
{ 
    throw e.WrapInFaultException(); 
} 

public static Exception WrapInFaultException(this Exception e) 
{ 
    var type = typeof(FaultException<>).MakeGenericType(e.GetType()); 

    return (Exception)Activator.CreateInstance(type, e); 
} 
+0

나는 이것을 게시하려고 생각했지만 FaultException의 생성자에 매개 변수로 exc을 어떻게 전달할 것인가? CreateInstance가 이것을 허용합니까? – Pandincus

+0

@Pandincus : 테스트하지는 않았지만 [Activator.CreateInstance (Type, Object \ [\]) (http://msdn.microsoft.com/en-us/library/wcxyzt4d)에 대한 호출을 믿습니다. aspx)는 그대로 작동해야합니다. – dtb

+0

절대로, 당신이 그 대답을 편집 한 것을 봅니다. 깔끔한 트릭! – Pandincus

1
public static void ThrowFaultException(this Exception exc) 
    { 
     // Gives me the correct type... 
     Type exceptionType = exc.GetType(); 
     var genericType = typeof(FaultException<>).MakeGenericType(exceptionType); 
     // But how the heck do I use it? 
     throw (Exception)Activator.CreateInstance(genericType, exc); 
    } 
관련 문제