C# 尽管创建了新对象,但对象引用未设置为对象的实例

C# 尽管创建了新对象,但对象引用未设置为对象的实例,c#,object,reference,C#,Object,Reference,我目前正在做一个基本的绘图程序。其中一个要求是能够保存绘制对象的列表并将其加载回。到目前为止,我已经编写了一个save函数,它将列表中的所有项导出为XML格式,目前我正在处理加载部分 每当程序遇到一个Dutch for RectangleTool时,它就会执行以下代码: //Create new tool. RechthoekTool tool = new RechthoekTool(); //Turn <Startpoint> and <Endpoint> into

我目前正在做一个基本的绘图程序。其中一个要求是能够保存绘制对象的列表并将其加载回。到目前为止,我已经编写了一个save函数,它将列表中的所有项导出为XML格式,目前我正在处理加载部分

每当程序遇到一个Dutch for RectangleTool时,它就会执行以下代码:

//Create new tool.
RechthoekTool tool = new RechthoekTool();

//Turn <Startpoint> and <Endpoint> into actual points
var sp = Regex.Replace(xn["Startpunt"].InnerText, @"[\{\}a-zA-Z=]", "").Split(',');
tool.startpunt = new Point(int.Parse(sp[0]), int.Parse(sp[1]));
var ep = Regex.Replace(xn["Eindpunt"].InnerText, @"[\{\}a-zA-Z=]", "").Split(',');
tool.eindpunt = new Point(int.Parse(ep[0]), int.Parse(ep[1]));

//Set colour and width of brush
string kleur = xn["Dikte"].InnerText;
kleur.Replace(@"Color [", "");
kleur.Replace(@"]", "");
Color c = Color.FromName(kleur);
tool.kwastkleur = c;
tool.kwast = new SolidBrush(c);
tool.dikte = int.Parse(xn["Dikte"].InnerText);

//Add to list
s.listItems.Add(tool);
每当我运行程序时,我都会得到“NullReferenceException was unhandled”errorObject reference未设置为对象的实例。在

s、 listItems.Addtool

然而,我确实在一开始就实例化了这个工具,不是吗?是什么导致了这个错误?一些谷歌用户告诉我这可能是因为我忘了分配财产,但据我所知,我已经把它们都包括在内了

非常感谢您的帮助。

此错误是由于未实例化s或s.listItems造成的


如果看不到更多的代码,很难知道哪个是空的,但是猜测一下,您正在为s创建一个新对象,其中包含一个属性/字段listItems,但您没有为listItems分配列表。

问题是您没有实例化listItems或s。没有提供足够的信息来告诉您如何实例化s,但您可以这样做:

s.listItems = new List<RechthoekTool>();
如果你不想用关键词做某事;这根本行不通

使用您的代码,尝试以下操作:

//Create new tool.
RechthoekTool tool = new RechthoekTool();

//Turn <Startpoint> and <Endpoint> into actual points
var sp = Regex.Replace(xn["Startpunt"].InnerText, @"[\{\}a-zA-Z=]", "").Split(',');
tool.startpunt = new Point(int.Parse(sp[0]), int.Parse(sp[1]));
var ep = Regex.Replace(xn["Eindpunt"].InnerText, @"[\{\}a-zA-Z=]", "").Split(',');
tool.eindpunt = new Point(int.Parse(ep[0]), int.Parse(ep[1]));

//Set colour and width of brush
string kleur = xn["Dikte"].InnerText;
kleur.Replace(@"Color [", "");
kleur.Replace(@"]", "");
Color c = Color.FromName(kleur);
tool.kwastkleur = c;
tool.kwast = new SolidBrush(c);
tool.dikte = int.Parse(xn["Dikte"].InnerText);

List<RechthoekTool> s = new List<RechthoekTool>();  // You can now use your list.
//Add to list
s.listItems.Add(tool);

正如David Arno在回答中所说的,检查s是否为null,以及s.listItems是否为null;listItems在另一个类中实例化,但我没有正确链接它。“它现在起作用了。@Biggar-如果大卫解决了你的问题,请接受他的回答!”!