为什么我会收到 NullException?
我搜索了一段时间,没有找到解决方案,还是我只是没有看到这个小错误?
我用 Visual C# 编写了一个程序 Form1.cs 程序.cs Server.cs
Server.cs
namespace WindowsApplication1 {
class testServer {
public Form1 form1;
form1.send("data");
Program.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Form1.cs
namespace WindowsApplication1
{
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
private testServer Server;
private void startServer_Click(object sender, System.EventArgs e)
{
Server = new Server(data);
Server.form1 = this;
}
一切正常,但在 Server.cs 中我得到一个 nullException form1.send("data");
看来 form1 确实为空,但为什么呢?
我哪里忘记了什么?
I searched a while and found no solution or do I just not see the little error?
I wrote a program with Visual C# and have
Form1.cs
Program.cs
Server.cs
Server.cs
namespace WindowsApplication1 {
class testServer {
public Form1 form1;
form1.send("data");
Program.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Form1.cs
namespace WindowsApplication1
{
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
private testServer Server;
private void startServer_Click(object sender, System.EventArgs e)
{
Server = new Server(data);
Server.form1 = this;
}
Everything works but in Server.cs I get a nullexception with form1.send("data");
It seems form1 is really null but why?
Where did I forget something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您必须创建 Form1 的实例,尝试
You have to create an instance of Form1, try
form1 永远不会被实例化。这是您的 NullReferenceException (NRE)。
更好的:
form1 is never instantiated. There is your NullReferenceException (NRE).
Better:
也许您忘记将
testServer
中的form1
变量分配给构造参数。顺便说一句:您的代码看起来不像好的设计:您不应该传递 Form 对象。
Maybe you forgot to assign the
form1
variable intestServer
to the construct parameter.BTW: You code doesn't look like good design: You shouldn't pass Form objects around.
它是空的,因为你没有初始化它。
It is null because you're not initializing it.
form1
变量在代码中使用之前未初始化The
form1
variable is not initialised before being used in the code