2011-11-17 3 views
4

메서드에 전달 된 예외 형식 매개 변수를 기반으로 예외를 throw하려고합니다.형식 매개 변수를 기반으로 새 개체 인스턴스화

public void ThrowException<T>(string message = "") where T : SystemException, new() 
    { 
     if (ConditionMet) 
     { 
      if(typeof(T) is NullReferenceException) 
       throw new NullReferenceException(message); 

      if (typeof(T) is FileNotFoundException) 
       throw new FileNotFoundException(message); 

      throw new SystemException(message); 
     } 
    } 

가 이상적으로 내가 SystemException의 기본 형식은 내가 가진 것 가지고 주어진 new T(message) 그런 짓을 할 : 여기

내가 지금까지 가지고 있지만 예외의 각 종류를 지정하지 않는 것입니다 이것이 어떻게 든 가능하다고 생각했습니다.

+0

이 할 수없는,하지만 해결 방법이 있습니다. 여기를 참고하십시오 : http://stackoverflow.com/questions/7772414/can-i-use-generic-constraints-to-enable-a-parameterized-constructor/7772426#7772426 –

+2

또한, 사용자 코드에서 NullReferenceException과 같은 예외를 throw합니다. –

답변

6

나는 당신이 gerics 혼자서 이것을 할 수 있다고 생각하지 않는다. 리플렉션을 사용해야합니다. 같은 : 당신은 http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx

+0

'객체'를 던질 수 없으므로'T' 또는'Exception'으로 캐스팅해야합니다. – Ray

+0

고마워요! 캐스트 – flipchart

+0

을 반영하도록 업데이트되었습니다. 형식이 예상 생성자를 지원하는지 명시 적으로 확인하고, 확인에 실패하면 의미있는 예외를 throw하는 것이 좋습니다. – Yaur

0

이 만 반사 수행 할 수 있습니다. 하지만 당신은 형식 매개 변수를 삭제하고 함수에 인스턴스화 예외를 전달할 수 :

public void ThrowException(Exception e) 
{ 
    if (ConditionMet) 
    { 
     if(e is NullReferenceException || e is FileNotFoundException) 
     { 
      throw e; 
     } 

     throw new SystemException(e.Message); 
    } 
} 

사용법 :

// throws a NullReferenceException 
ThrowException(new NullReferenceException("message")); 
// throws a SystemException 
ThrowException(new NotSupportedException("message")); 
1

다른 사람이 언급 한 바와 같이에서

Activator.CreateInstance(typeof(T),message); 

더 사용할 수 있습니다

throw (T)Activator.CreateInstance(typeof(T),message); 
관련 문제