我无法理解为什么我的代码无法正常运行。我创建了两个类,Main和Labels,我想通过调用Main中的Labels类打印出标签。它给了我一个运行时错误。我感谢您提供的任何帮助。
//--------------------------------------------------main class-------------------//
namespace Test
{
public partial class Form1 : Form
{
labels label;
public Form1()
{
InitializeComponent();
createLabel();
}
private void createLabel()
{
//error "Object reference not set to an instance of an object"
label.printHeader();
}
}//form
}//test
// ---------------------------------- labels class-------------------------//
namespace Test
{
class labels
{
private Label label1;
public labels()
{
}
public void printHeader()
{
label1 = new Label();
label1.Location = new System.Drawing.Point(82, 44);
label1.Size = new System.Drawing.Size(977, 54);
label1.Text = "MonthCalendar";
Controls.Add(label1);
}
}//form
}//test
答案 0 :(得分:3)
您声明了类,但从不创建实例。
尝试
private void createLabel()
{
label = new labels();
label.printHeader();
}
答案 1 :(得分:1)
Just instanciate
private void createLabel()
{
label = new labels();
//error "Object reference not set to an instance of an object"
label.printHeader();
}
答案 2 :(得分:1)
private void createLabel()
{
label =new labels();//add this
//error "Object reference not set to an instance of an object"
label.printHeader();
}