我是C#的新手,也是C ++(大学一年级编程)的相同经验。最近我们开始使用C#,我想做的事情是使用印刷电路板的简单游戏(到目前为止,我只使用控制台应用程序)。我开始挖掘(我将链接到下面的主题)。
我正在使用Visual Studio Ultimate 2013.我想制作的主板是简单的按钮板(但具有额外的属性)。所以我创建了一个继承自按钮并开始添加一些东西的类(会有更多):
class Field : Button
{
private string owner;
private string temp_owner;
private int level;
private int temp_level;
public Field() : base()
{
owner = "brak";
temp_owner = owner;
level = 0;
temp_level = level;
}
}
然后我查看了按钮的初始化方式(在Form1.Designer.cs中),但Visual Studio不允许我在那里写任何内容,所以我创建了方法build_board并将其放在Form1.cs中:
public partial class main_form : Form
{
public main_form()
{
InitializeComponent();
build_board();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private System.Windows.Forms.Button [,] Board;
private void build_board()
{
this.Board = new Field[10, 10];
this.SuspendLayout();
//
// Board
//
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
{
this.Board[i, j].BackColor = System.Drawing.SystemColors.Control;
this.Board[i, j].Location = new System.Drawing.Point(10 + i * 10, 10 + j * 10);
this.Board[i, j].Name = "Field [ " + i + " , " + j + " ]";
this.Board[i, j].Size = new System.Drawing.Size(50, 50);
this.Board[i, j].TabIndex = 100 * i + j;
this.Board[i, j].Text = "";
this.Board[i, j].UseVisualStyleBackColor = false;
}
this.ResumeLayout(false);
}
}
问题是调试器正在尖叫&#34; NullReferenceException未处理&#34;在这一行:
this.Board[i, j].BackColor = System.Drawing.SystemColors.Control;
我已经检查了一些其他主题,他们说这可能是由于董事会没有初始化而引起的,但我认为我做了初始化。我将非常感谢您提供有关如何轻松打印自定义对象数组的任何帮助和其他一些提示。
我的研究:
C# NullReferenceException was unhandled - Object reference not set to an instance of an object
NullReferenceException was unhandled C#
How to create an array of custom type in C#?
(还有许多其他关于印刷的内容)
编辑:
回答Pazi01: 在循环中需要添加这两行:
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
{
this.Board[i, j] = new Field();
this.Controls.Add(this.Board[i, j]);
...
}
答案 0 :(得分:0)
原因是您没有初始化数组中的数据
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
{
this.Board[i, j] = new Field();
this.Board[i, j].BackColor = System.Drawing.SystemColors.Control;
this.Board[i, j].Location = new System.Drawing.Point(10 + i * 10, 10 + j * 10);
this.Board[i, j].Name = "Field [ " + i + " , " + j + " ]";
this.Board[i, j].Size = new System.Drawing.Size(50, 50);
this.Board[i, j].TabIndex = 100 * i + j;
this.Board[i, j].Text = "";
this.Board[i, j].UseVisualStyleBackColor = false;
}
我插入了这个:
this.Board[i, j] = new Field();
修改强> 您还必须将控件添加到表单
this.Controls.Add(this.Board[i, j]);