[英]Object reference not set to an instance of an object error?
在我的C#程序中,我要尝试做的就是在游戏中每当您说出!mypickaxe时,它就会告诉您所拥有的镐。 最近,我想出了一种将其保存到.txt文件的方法,以便可以多次使用数据,但是当然会收到“对象引用未设置为对象实例”的信息。 这是有错误的部分:
StreamReader streemy = new StreamReader("pickaxes.txt");
string line = streemy.ReadLine();
string[] thing = line.Split('=');
player[userID].pickaxe = Convert.ToInt32(thing[1]);
在.txt文件中,它像这样保存:username = pickaxe因此,它应该获取数字,但是我在这一行得到了该错误:
string[] thing = line.Split('=');
有人知道如何解决此问题和/或为什么会这样吗? 提前致谢!
尝试检查streemy.ReadLine
返回null:
string line = streemy.ReadLine();
if(!string.IsNullOrEmpty(line))
{
string[] thing = line.Split('=');
player[userID].pickaxe = Convert.ToInt32(thing[1]);
}
您甚至可以进一步检查thing
和player[userID]
if(!string.IsNullOrEmpty(line))
{
string[] thing = line.Split('=');
if(thing.Count() > 1 && player[userID] != null)
player[userID].pickaxe = Convert.ToInt32(thing[1]);
}
我也将流包装在using
块中:
using(StreamReader streemy = new StreamReader("pickaxes.txt"))
{
//code omitted
}
我建议使用File.ReadAllLines()
以避免所有错误。
string [] line=System.IO.File.ReadAllLines("pickaxes.txt");
string[] thing = line[0].Split('=');//here 0 can be any required index
player[userID].pickaxe = Convert.ToInt32(thing[1]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.