C# 从引用调用创建标签
我不明白为什么我的代码不起作用。我创建了两个类,Main和Labels,我想通过在Main中调用Labels类来打印标签。它给了我一个运行时错误。我感谢你能提供的任何帮助C# 从引用调用创建标签,c#,label,C#,Label,我不明白为什么我的代码不起作用。我创建了两个类,Main和Labels,我想通过在Main中调用Labels类来打印标签。它给了我一个运行时错误。我感谢你能提供的任何帮助 //--------------------------------------------------main class-------------------// namespace Test { public partial class Form1 : Form { labels lab
//--------------------------------------------------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=新标签()在调用createLabel()之前,请将代码>添加到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();
}