【问题标题】:Why do I get NullException?为什么我得到空异常?
【发布时间】:2012-03-12 14:36:05
【问题描述】:

我搜索了一段时间并没有找到解决方案,还是我没有看到这个小错误?

我用 Visual C# 编写了一个程序,并且有 Form1.cs 程序.cs 服务器.cs

服务器.cs


namespace WindowsApplication1 {
class testServer {
public Form1 form1;
form1.send("data");

程序.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 中,form1.send("data"); 出现空异常 看来form1真的是空的,但为什么呢?

我在哪里忘记了什么?

【问题讨论】:

  • form1.send("data"); 不在函数内部。

标签: c# exception null


【解决方案1】:

你要创建Form1的实例,试试

public Form1 form1 = new Form1();

【讨论】:

  • 好的,这帮助我继续 =) 谢谢。以为已经在那里完成了。
【解决方案2】:
public Form1 form1;
form1.send("data");

form1 永远不会被实例化。有你的 NullReferenceException (NRE)。

更好:

public Form1 form1 = new Form1();
form1.send("data");

【讨论】:

    【解决方案3】:

    可能你忘了把testServer中的form1变量赋值给construct参数。

    顺便说一句:你的代码看起来不像是好的设计:你不应该传递 Form 对象。

    【讨论】:

      【解决方案4】:

      它是空的,因为你没有初始化它。

      public Form1 form1;
      ..
      // Initialize the object BEFORE using it!
      form1 = new Form1();
      form1.send("data");
      

      【讨论】:

      • "WindowsApplication1.SocketServer.form1" 不是一个字段,但是被使用了......这个方法必须有一个返回类型或类似的东西
      【解决方案5】:

      form1 变量在代码中使用之前未初始化

      【讨论】:

        猜你喜欢
        • 2011-12-13
        • 2011-04-14
        • 2018-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多