2013-07-05 4 views
1

내 정적 생성자가 실패하고 확장 메서드가 여전히 작동해도 예외를 throw하는 경위가 궁금하십니까? 로거는 확장 메서드의 문제를 감지하는 데 도움을주기위한 것입니다. 만약 그들이 여전히 작동하지 않는다면 나는 포획을 시도하고 생성자가 성공했는지 확인해야 할 것이다. 코드를 호출하면 오류를 기록 할 수 있기 때문에 예외가 발생하는 것을 선호 할 수 있습니다.정적 생성자 및 확장 메서드

 public static class Extensions 
    { 

     private static readonly log4net.ILog log; 
     private const TIME_TO_CHECK; 

     static Extensions() 
     { 
      log = log4net.LogManager.GetLogger   (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //could maybe throw exception 

      TIME_TO_CHECK = readInFromFile(); //could maybe   throw       exception   }   

     public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek) { 
     int diff = dt.DayOfWeek - startOfWeek; 
     if (diff < 0) { 
     diff += 7; 
     } 
     return dt.AddDays(-1 * diff).Date; 
    } 
    } 

나는 (희망이 반복되지 않습니다) 주위를 검색했고, 정적 생성자에서 예외를 던지는 것은 일반적으로 좋지 않은 것으로 나타났습니다 (이것은 내가 대해 생각하고있는 것과 유사한 단지 예제 코드이다). 대부분의 경우 클래스는 인스턴스화 될 수 있고 모든 확장 메서드가 아닌 클래스라고 생각합니다.

답변

5

내 정적 생성자가 실패하고 확장 메서드가 여전히 작동하는 경우 예외를 throw하는 경탄?

아니요. 모든 유형의 초기화 프로그램 (정적 생성자 사용 여부와 상관없이)이 실패하면 기본적으로 그 유형을 사용할 수 없습니다.

그것은이를 입증 할 매우 쉽습니다 ...

using System; 

static class Extensions 
{ 
    static Extensions() 
    { 
     Console.WriteLine("Throwing exception"); 
     throw new Exception("Bang"); 
    } 

    public static void Woot(this int x) 
    { 
     Console.WriteLine("Woot!"); 
    } 
} 

class Test 
{ 

    static void Main() 
    { 
     for (int i = 0; i < 5; i++) 
     { 
      try 
      { 
       i.Woot(); 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine("Caught exception: {0}", e.Message); 
      } 
     } 
    } 
} 

출력 :

+0

. 바라기를 그것은 다른 누군가를 돕는다. –

+0

이 스마트했을 것이다 노력 주셔서 감사합니다 좋은 예입니다

Throwing exception Caught exception: The type initializer for 'Extensions' threw an exception. Caught exception: The type initializer for 'Extensions' threw an exception. Caught exception: The type initializer for 'Extensions' threw an exception. Caught exception: The type initializer for 'Extensions' threw an exception. Caught exception: The type initializer for 'Extensions' threw an exception. 
Travis