[英]Object reference not set to an instance of an object error?
and in my c# program, what i am trying to do is whenever in a game you say !mypickaxe, it tells you what pickaxe you have. 在我的C#程序中,我要尝试做的就是在游戏中每当您说出!mypickaxe时,它就会告诉您所拥有的镐。 Recently I figured out a way to save it to a .txt file so the data could be used more than one time, but of course im getting "object reference not set to an instance of an object". 最近,我想出了一种将其保存到.txt文件的方法,以便可以多次使用数据,但是当然会收到“对象引用未设置为对象实例”的信息。 Here is the part that has the error: 这是有错误的部分:
StreamReader streemy = new StreamReader("pickaxes.txt");
string line = streemy.ReadLine();
string[] thing = line.Split('=');
player[userID].pickaxe = Convert.ToInt32(thing[1]);
In the .txt file, it saves like this: username=pickaxe And so it's supposed to get the number, but i get that error on this line: 在.txt文件中,它像这样保存:username = pickaxe因此,它应该获取数字,但是我在这一行得到了该错误:
string[] thing = line.Split('=');
Does anybody know how to fix this and/or why this happens? 有人知道如何解决此问题和/或为什么会这样吗? Thanks in advance! 提前致谢!
try and check if streemy.ReadLine
returns null: 尝试检查streemy.ReadLine
返回null:
string line = streemy.ReadLine();
if(!string.IsNullOrEmpty(line))
{
string[] thing = line.Split('=');
player[userID].pickaxe = Convert.ToInt32(thing[1]);
}
you could even go futher and check thing
and player[userID]
您甚至可以进一步检查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]);
}
also I would wrap the stream in a using
block: 我也将流包装在using
块中:
using(StreamReader streemy = new StreamReader("pickaxes.txt"))
{
//code omitted
}
i would suggest to use File.ReadAllLines()
to avoid all Errors. 我建议使用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.