未处理类型异常(System.TypeInitializationException)
本文关键字:TypeInitializationException System 类型 异常 未处理 | 更新日期: 2023-09-27 18:08:59
正如标题所说,Visual Studio在执行程序时抛出异常。确切的错误:
An unhandled exception of type 'System.TypeInitializationException' occurred in mscorlib.dll
由于我对使用Visual Studio和c#相当陌生,因此我无法辨别问题是什么。我用谷歌搜索了一下,但没有任何信息能帮助我恢复这个异常程序。
程序代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Game {
public struct entity {
int XP,
HP,
mana,
luck,
strength,
defense;
float modStrength,
modDefense;
string stance;
}
public class Game {
private entity enemy;
private static Dictionary<string, int> playerData =
new Dictionary<string, int>();
public static string[] entityPool =
new StreamReader(Properties.Resources.Entities).ToString().Split('?');
static void Main (string[] args) {
instancePlayer();
Console.ReadKey();
}
private static void instancePlayer () {
string[] playerDataDummy = entityPool[0].Trim().Split(';');
foreach (string s in playerDataDummy) {
string[] indivArr = s.Split(' ');
playerData.Add(indivArr[0], Convert.ToInt16(indivArr[1]));
}
foreach (KeyValuePair<string, int> s in playerData) {
Console.WriteLine("[{0}] {1}", s.Key, s.Value);
}
}
private void instanceEnemy () {
}
}
}
我已经能够将问题缩小到这一行,尽管…
public static string[] entityPool = new StreamReader(Properties.Resources.Entities).ToString().Split('?');
这是我所发现的最多的;删除它的初始化,以及它的所有引用,将使问题无效。但是,唉,我确实需要它。
看一下MSDN上的streamreader类。它有几个构造函数,还有一个从文本文件中读取的简单示例。我不确定Properties.Resources.Entities(我假设是一个文件路径)中有什么。假设这是一个有效的文件路径或流,并且构造函数没有抛出错误,您正在创建streamreader,然后调用. tostring(),该方法将为您提供streamreader对象的字符串表示形式,而不是文件或流的内容。这可能不是你所期望的。MSDN页面上的示例应该帮助您使用StreamReader类。
这一行不对。
public static string[] entityPool = new StreamReader(Properties.Resources.Entities).ToString().Split('?');
您的意思可能是读取流的所有内容。像这样。
StreamReader sr = new StreamReader(Properties.Resources.Entities);
string[] entityPool = sr.ReadToEnd().Split('?');
最好将这段代码放在构造函数中并使用try-catch,而不是放在初始化器中。
似乎不需要StreamReader来访问文件的内容。
string[] entityPool = Properties.Resources.Entities.split('?');
按我先前的预期工作。
感谢大家的回复。