& # 39; System.TypeInitializationException& # 39;在以前工作的代码上抛出

本文关键字:代码 System TypeInitializationException 工作 | 更新日期: 2023-09-27 18:13:23

我的代码以前工作得很好,但现在当我运行它;它会抛出这个异常:

类型为"System"的未处理异常。TypeInitializationException"内附加信息:类型'varBank'的初始化器抛出异常。

更奇怪的是,除了添加这个类之外,我什么也没改变:

public class readParameters
{
    public static void readLog(int start, int end)
    {
        for (int x = start; x < end; x++)
        {
        }
    }
    public static void nextLine()
    {
        string[,] logArr = new string[4, 5];
    }
}

问题行在

下面的块中突出显示。
/// </data bank>
public class varBank
{
    public static string logInput { get; set; }
    public static PathType FilePath { get; private set; }
    public static EventLogReader evl = new EventLogReader(logInput, FilePath);
    public static EventRecord bsnRecord = evl.ReadEvent();
}
/// </data bank>
namespace EventLogInfoReader
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Log Location: ");
          varBank.logInput = Console.ReadLine();
            Console.WriteLine("Enter Read Parameters: ");
            int i = 1;
            while (++i > 0)
            {
                Console.WriteLine("Enter Property: ");
                string CommandInput = Console.ReadLine();
                getInfo.callInfo(CommandInput);
            }
        }
    }
}

& # 39; System.TypeInitializationException& # 39;在以前工作的代码上抛出

该异常表示从静态构造函数或字段初始化项抛出异常。我怀疑它在evl的初始化器中,因为它引用了没有初始值设置的静态属性(它们将是null)。

我会把代码移到静态构造函数中,这样你就可以更好地处理错误和/或记录日志。evlbsnRecord都有静态初始化器,这些初始化器容易受到运行时异常的影响,不应该被检查。

我也质疑为什么你的静态属性是用其他静态属性初始化的。如果客户端代码设置了FilePath属性,您期望发生什么?

相关文章: