什么是"未处理的类型' System.TypeInitializationException'发生在mscorlib.dll"

时间:2016-01-04 00:44:18

标签: c# winforms

这是我第一次在编码时遇到这种错误,当我搜索这个错误时,提供的答案非常模糊,对我来说不是很有用。所以我实际构建了这个窗体应用程序,并且我已经创建了几个类。我之前没有遇到过这个问题而且它突然发生了,而且我没有触及它所做的事情。

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    /// 

    public static store myStore = new store();

    [STAThread]

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

当我注释掉公共静态存储myStore = new store();我可以运行该程序,但我的Windows窗体应用程序

上没有任何内容被初始化

这是商店类:

    class storeSystem
{
    // Creates a list to store cards (cards)
    public List<cardObject> myCardList = new List<cardObject>();

    // Creates a list to store image paths
    public List<string> imagePathList = new List<string>();

    public storeSystem()
    {
        createCardObject();
        initialisePicture();
    }

    public void createCardObject()
    {
        // Get data from txt file
        string[] cardInfo = System.IO.File.ReadAllLines(@"F:\Assignment\cardLists.txt");

        // Populate "cards" list
        for (int i = 0; i < cardInfo.Length; i++)
        {
            string[] cardData = cardInfo[i].Split(',');
            myCardList.Add(new cardObject(cardData[1], cardData[2], int.Parse(cardData[3]), double.Parse(cardData[4])));
        }
    }

    public void initialisePicture()
    {
        // Get image path from txt file
        string[] imagePath = System.IO.File.ReadAllLines(@"F:\Assignment\imagePath.txt");
    }
}

对格式化感到抱歉!

2 个答案:

答案 0 :(得分:2)

因此,您的错误是I / O错误(这些文件中的一个或两个都不存在或无法访问等)或cardLists.txt的内容。更重要的是,一行(或多行)不会分成五个不同的字符串部分(cardData[0] - 奇怪地未使用;这可能是您问题的一部分。)

然而,最大的问题是整体设计问题 - 构造函数不应该进行大量处理,因此抛出您不知道的异常。实际上不应该由构造函数调用createCardObjectinitialisePicture

无论如何,在Visual Studio中,在构造函数的第一行设置一个断点,然后在实际崩溃的情况下设置F11,你将获得完整的异常文本并知道它在做什么它

答案 1 :(得分:1)

TypeInitializationException被抛出作为类初始化程序抛出的异常的包装器。

在初始化调用构造函数期间的代码类Programstore填充静态字段myStore

我可以在storeSystem类型的构造函数中看到四个可能的异常:

  1. 文件F:\Assignment\cardLists.txt可能会丢失或受到保护而无法读取(FileNotFoundException,IOException,...)。

  2. 文件行的
  3. Split可以返回少于四个元素的数组(IndexOutOrRange)。你确定应该跳过spited数组的第一个元素吗?

  4. int.Parse如果不是整数,可能会抛出解析异常。

  5. 文件F:\Assignment\imagePath.txt可能会丢失或无法阅读。

  6. 要找出确切的原因检查内部异常,或者只是在storeSystem的构造函数中调试解决方案。

    将来考虑避免可能在构造函数中抛出异常的操作,特别是在静态构造函数中,并且可能会添加一些验证逻辑或try/catch来打开文件。