2016-04-15 37 views
1

當我嘗試在類的靜態構造函數中填充泛型列表時,出現第9行的System.TypeInitializationException異常。c#TypeInitializationException在初始化靜態構造函數中的泛型集合時

using System; 
using System.Collections.Generic; 

namespace ConsoleApplication5_static_constructor { 
    public static class DataRepository { 
     public static List<DefinedField> Tables; 
     static DataRepository() { 
      Console.WriteLine("static DataRepository constructor fired"); 
      Tables.Add(new DefinedField("ID")); **//this is line 9** 
     } 
    } 

    public class DefinedField { 
     string _tableName; 
     public DefinedField(string tableName) { 
     _tableName = tableName; 
    } 

     public string TableName { 
      get { return _tableName; } 
      set { _tableName = value; } 
     } 

    } 
} 

呼叫代碼:

using System.Collections.Generic; 

namespace ConsoleApplication5_static_constructor { 
    class Program { 
     static void Main(string[] args) { 
      List<DefinedField> x = DataRepository.Tables; 
     } 
    } 
} 

到底是什麼導致了錯誤,如何解決這個問題,好嗎?

編輯:也有一個類型爲NullReferenceException的內部異常 靜態構造函數是否無法初始化新對象?

+0

通常,當你得到異常,你不明白看看InnerException。這可能是一個NullReferenceException,它會告訴你原因。 – CathalMF

+0

謝謝,下次我會記住這一點。我很高興你們幫助我這麼快。其實它會花費我一些時間來解決這個問題,可能是因爲我更習慣於編寫python腳本 – kitty

+0

@CathalMF通常是的,但是當靜態構造函數中發生異常時不行。 – Maarten

回答

4

您的靜態屬性Tables未初始化。它顯示爲TypeInitializationException,因爲異常在靜態構造函數中觸發。因此,當DataRepository正在初始化時發生異常。

解決方法是將其設置爲空列表。

public static List<DefinedField> Tables = new List<DefinedField>(); 
+0

哎呀謝謝! - 要等幾分鐘才能接受這個答案:) – kitty

相關問題