當我嘗試在類的靜態構造函數中填充泛型列表時,出現第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的內部異常 靜態構造函數是否無法初始化新對象?
通常,當你得到異常,你不明白看看InnerException。這可能是一個NullReferenceException,它會告訴你原因。 – CathalMF
謝謝,下次我會記住這一點。我很高興你們幫助我這麼快。其實它會花費我一些時間來解決這個問題,可能是因爲我更習慣於編寫python腳本 – kitty
@CathalMF通常是的,但是當靜態構造函數中發生異常時不行。 – Maarten