2012-02-22 112 views
0

我搜索了一段时间,发现没有解决方案,或者我只是没有看到小错误?为什么我会得到NullException?

我写了一个程序使用Visual C#和有 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; 

    } 

一切正常,但在Server.cs我得到form1.send("data"); 一个nullexception看来form1的是真的空,但为什么呢?

我在哪里忘记了什么?

+1

'form1.send( “数据”)在使用前初始化;'不在函数内部。 – 2012-02-22 09:12:51

回答

4

你必须创建Form1的一个实例,尝试

public Form1 form1 = new Form1(); 
+0

好吧,这有助于我继续=)谢谢。认为它已经在那里完成了。 – 2012-02-22 09:19:03

2
public Form1 form1; 
form1.send("data"); 

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

更好:

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

也许你忘记了form1变量testServer分配给结构参数。

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

1

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

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

“WindowsApplication1.SocketServer.form1”不是一个字段,但使用... 这种方法必须有一个返回类型或类似的东西 – 2012-02-22 09:16:01

0

form1变量没有在代码