这是我第一次在编码时遇到这种错误,当我搜索这个错误时,提供的答案非常模糊,对我来说不是很有用。所以我实际构建了这个窗体应用程序,并且我已经创建了几个类。我之前没有遇到过这个问题而且它突然发生了,而且我没有触及它所做的事情。
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");
}
}
对格式化感到抱歉!
答案 0 :(得分:2)
因此,您的错误是I / O错误(这些文件中的一个或两个都不存在或无法访问等)或cardLists.txt
的内容。更重要的是,一行(或多行)不会分成五个不同的字符串部分(cardData[0]
- 奇怪地未使用;这可能是您问题的一部分。)
然而,最大的问题是整体设计问题 - 构造函数不应该进行大量处理,因此抛出您不知道的异常。实际上不应该由构造函数调用createCardObject
和initialisePicture
。
无论如何,在Visual Studio中,在构造函数的第一行设置一个断点,然后在实际崩溃的情况下设置F11,你将获得完整的异常文本并知道它在做什么它
答案 1 :(得分:1)
TypeInitializationException被抛出作为类初始化程序抛出的异常的包装器。
在初始化调用构造函数期间的代码类Program
或store
填充静态字段myStore
。
我可以在storeSystem
类型的构造函数中看到四个可能的异常:
文件F:\Assignment\cardLists.txt
可能会丢失或受到保护而无法读取(FileNotFoundException,IOException,...)。
Split
可以返回少于四个元素的数组(IndexOutOrRange)。你确定应该跳过spited数组的第一个元素吗?
int.Parse
如果不是整数,可能会抛出解析异常。
文件F:\Assignment\imagePath.txt
可能会丢失或无法阅读。
要找出确切的原因检查内部异常,或者只是在storeSystem
的构造函数中调试解决方案。
将来考虑避免可能在构造函数中抛出异常的操作,特别是在静态构造函数中,并且可能会添加一些验证逻辑或try/catch
来打开文件。