Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从引用调用创建标签_C#_Label - Fatal编程技术网

C# 从引用调用创建标签

C# 从引用调用创建标签,c#,label,C#,Label,我不明白为什么我的代码不起作用。我创建了两个类,Main和Labels,我想通过在Main中调用Labels类来打印标签。它给了我一个运行时错误。我感谢你能提供的任何帮助 //--------------------------------------------------main class-------------------// namespace Test { public partial class Form1 : Form { labels lab

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

 private void createLabel()
     {
        label = new labels();        
 //error "Object reference not set to an instance of an object"
        label.printHeader();
     }

声明类,但从不创建实例

试一试


您必须首先实例化标签。尝试添加
label=新标签()添加到Form1构造函数中。类名应为CamelCase。请在回答中添加一些解释。仅粘贴代码不是很有用。
private void createLabel()
     {
        label =new labels();//add  this
        //error "Object reference not set to an instance of an object"
        label.printHeader();
     }
 private void createLabel()
 {
    label = new labels();
    label.printHeader();
 }