输入字符串导致nullreferenceexception的错误是什么?
本文关键字:错误 是什么 nullreferenceexception 字符串 输入 | 更新日期: 2023-09-27 18:16:22
问题是else情况,我已经在问题行
上进行了注释 static void Main(string[] args)
{
XMLData xmldataExample = new XMLData();
Usergaz usergazExample = new Usergaz();
UsergazItem usergazitemExample = new UsergazItem();
UsergazItem item = new UsergazItem();
string filename = @"C:'Users'565133'Desktop'test.xml";
Deserialize<XMLData> deserializeobj = new Deserialize<XMLData>();
Console.WriteLine("Choose 'n1.Serialization'n2.Deserialization'n3.Deserialize only a token");
//It works when I give tknid input line here
int inp = Console.Read();
string tknid = Console.ReadLine();//It doesn't work if I get tknid input here
if (inp == 1)
{
usergazitemExample.getusergazitem();
usergazExample.getusergaz();
usergazExample.gazitem.Add(usergazitemExample);
xmldataExample.getxmldata();
xmldataExample.gazset.Add(usergazExample);
serial(xmldataExample, filename);
Console.WriteLine("Its done");
Console.ReadKey();
}
else if (inp == 2)
{
Console.WriteLine("Getting data from xml file");
// Deserialize<XMLData> deserializeobj = new Deserialize<XMLData>();
xmldataExample = deserializeobj.deserializefunction(filename);
List<Usergaz> samplelist = new List<Usergaz>();
samplelist = xmldataExample.gazset;
MTable.initialize();
MTable.usergazzetterset.Add(xmldataExample.updatedtime, samplelist);
Console.WriteLine("Deserialization complete, check the object");
Console.ReadKey();
}
在这个else情况下,我使用tknid进行过滤,但甚至在我从用户输入tknid之前,我得到nullreference异常,说'item'对象是空的。我得到指向控制台的异常。WriteLine行
else
{
//Console.WriteLine("Getting only a specific token Enter the token id");
//string tknid;
//tknid = Console.ReadLine();
//I intended to give tknid input here, but I cannot do it...
//Console.WriteLine(tknid);
//Console.ReadKey();
//string tknid = "3"; Initializing tknid with this statement works fine
item = deserializeobj.deserializefunction(filename).gazset[0].gazitem.Where(X => X.id == tknid).FirstOrDefault();
Console.WriteLine("The value for the token id {0} is {1}", tknid,item.val);
Console.ReadKey();
}
}
我已经得到了解决方案,问题不是与if…else语句,而是与Console.Read()。
我用int inp = int.Parse(Console.ReadLine())
代替了int inp = Console.Read()
,它工作得很好。
现在我明白了Console.Read()
是如何工作的,我在下面分享了一个答案的帮助下,但我永远不会尝试使用Console.Read()
,并且总是使用Console.ReadLine()
。
Console.Read()
如何工作: