0

私は現在、基本的な描画プログラムに取り組んでいます。要件の 1 つは、描画されたオブジェクトのリストを保存して、再度読み込むことができることです。これまでのところ、リストのすべての項目を XML 形式にエクスポートする保存関数を作成しました。現在、ローディング部分。

プログラムが "< RechthoekTool >" (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」エラー (「オブジェクト参照がオブジェクトのインスタンスに設定されていません」) が発生します。

s.listItems.Add(ツール);

ただし、最初にツールをインスタンス化しますね。このエラーの原因は何ですか? 一部のグーグルは、プロパティを割り当てるのを忘れたことが原因かもしれないと言っていましたが、私が知る限り、それらはすべてカバーされています...

助けていただければ幸いです。

4

3 に答える 3

9

エラーの原因は、インスタンス化されていないことですss.listItems

これ以上のコードを見ないと、どれが null であるかを知るのは困難ですが、推測sでは、 property/field を含む の新しいオブジェクトを作成してlistItemsいますが、リストを に割り当てていませんlistItems

于 2013-11-04T20:48:24.460 に答える
2

問題は、インスタンス化listItemsまたはs. インスタンス化する方法を説明するのに十分な情報は提供されてsいませんが、次のように他の方法を実行できます。

s.listItems = new List<RechthoekTool>();
于 2013-11-04T20:49:00.030 に答える
1

newキーワードを使用して何かをインスタンス化しない場合。それは単に機能しません。

コードを使用して、これを試してください:

//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);
于 2013-11-04T21:00:26.557 に答える