当我尝试在类的静态构造函数中填充泛型列表时,出现第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