2012-02-22 111 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變量沒有在代碼