-2

我不明白为什么我的代码不起作用。我创建了两个类,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
4

3 回答 3

3

您声明了类,但从不创建实例。

尝试

 private void createLabel()
 {
    label = new labels();
    label.printHeader();
 }
于 2012-09-04T17:18:52.027 回答
1

只是实例化

 private void createLabel()
     {
        label = new labels();        
 //error "Object reference not set to an instance of an object"
        label.printHeader();
     }
于 2012-09-04T17:18:19.800 回答
1
private void createLabel()
     {
        label =new labels();//add  this
        //error "Object reference not set to an instance of an object"
        label.printHeader();
     }
于 2012-09-04T17:18:20.060 回答