【发布时间】:2016-04-15 08:07:58
【问题描述】:
在运行此代码时,我在第 9 行遇到 System.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,它会告诉你原因。
-
谢谢,下次我会记住这一点。我很高兴你们这么快就帮助了我。其实这需要我一段时间才能弄清楚,可能是因为我更习惯于编写 python 脚本
-
@CathalMF 通常是,但在静态构造函数中发生异常时不会。
-
@Maarten 我自己重新创建了它,它在 InnerException 中有一个 NullReferenceException
标签: c# constructor static