2013-07-05 69 views
1

想知道如果我的靜態構造函數失敗並拋出異常,如果擴展方法仍然工作?記錄器旨在幫助檢測擴展方法中的問題。如果他們不能繼續工作,我將不得不嘗試趕上並確保構造函數成功。我希望能夠拋出異常,希望調用代碼可以記錄錯誤。 (這是類似於我在想剛纔的例子代碼)靜態構造函數和擴展方法

 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

想知道如果我的靜態構造函數失敗,並拋出異常,如果擴展方法仍然工作?

否。如果任何類型的初始值設定項(無論是否使用靜態構造函數)都失敗,則此類型基本上不可用。

這很容易證明這一點......

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); 
      } 
     } 
    } 
} 

輸出:

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. 
+0

這是一個很好的例子 –

+0

謝謝你想它會一直聰明。希望它可以幫助別人。 – Travis