System.TypeInitializationException 关于设置静态 public 变量
System.TypeInitializationException on setting a static public variable
在同一个命名空间中我有这两个函数
public static class DAL
{
public static bool SHOWMESSAGES = false;
private static StreamWriter logger = new StreamWriter(logLocation); // line 4
}
class testmain
{
static public void Main(string[] args)
{
DAL.SHOWMESSAGES = true; //line 5
}
}
如果我运行这个代码我会得到一个"An unhandled exception of type 'System.TypeInitializationException' occurred"。可能是什么原因造成的?
在 .NET 中,类型不会在应用程序启动时初始化,而是在您第一次访问该类型时初始化。在您的情况下,它可能位于第 5 行:DAL.SHOWMESSAGES = true;
在执行此语句之前,DAL
class 必须进行初始化。执行静态构造函数并将所有静态字段设置为其默认值。如果失败,你会得到 TypeInitializationException
.
我建议您避免使用静态构造函数和具有默认值的静态字段,例如private static _someField = new SomeClass();
我的情况可能是这样的:
public static class DAL
{
public static bool SHOWMESSAGES = false;
private static StreamWriter logger;
public static void Initialize()
{
logger = new StreamWriter(....);
}
}
甚至更好,完全避免静态 class:
public class DAL
{
public bool ShowMessages { get; set; }
private StreamWriter logger;
public DAL()
{
logger = new StreamWriter(....);
}
}
class testmain
{
static DAL dal;
static public void Main(string[] args)
{
dal = new DAL();
dal.ShowMessages = true;
}
}
在同一个命名空间中我有这两个函数
public static class DAL
{
public static bool SHOWMESSAGES = false;
private static StreamWriter logger = new StreamWriter(logLocation); // line 4
}
class testmain
{
static public void Main(string[] args)
{
DAL.SHOWMESSAGES = true; //line 5
}
}
如果我运行这个代码我会得到一个"An unhandled exception of type 'System.TypeInitializationException' occurred"。可能是什么原因造成的?
在 .NET 中,类型不会在应用程序启动时初始化,而是在您第一次访问该类型时初始化。在您的情况下,它可能位于第 5 行:DAL.SHOWMESSAGES = true;
在执行此语句之前,DAL
class 必须进行初始化。执行静态构造函数并将所有静态字段设置为其默认值。如果失败,你会得到 TypeInitializationException
.
我建议您避免使用静态构造函数和具有默认值的静态字段,例如private static _someField = new SomeClass();
我的情况可能是这样的:
public static class DAL
{
public static bool SHOWMESSAGES = false;
private static StreamWriter logger;
public static void Initialize()
{
logger = new StreamWriter(....);
}
}
甚至更好,完全避免静态 class:
public class DAL
{
public bool ShowMessages { get; set; }
private StreamWriter logger;
public DAL()
{
logger = new StreamWriter(....);
}
}
class testmain
{
static DAL dal;
static public void Main(string[] args)
{
dal = new DAL();
dal.ShowMessages = true;
}
}