2014-01-31 36 views
0

如果我的標題問題文本不正確,我表示歉意...... 我的問題: 第一類發佈的工作正常,我可以通過發送數據到控制處理器Crestron.ActiveCNX。顯示包含「Hello world」的行將數據發送到控制處理器,並且在這裏工作正常。在這個班裏,我開始了這個ActiveCNX通信,還有事件處理(這裏沒有顯示)。 但是我有很多代碼,需要通過這個來自另一個類的ActiveCNX連接發送數據。這個類將顯示必要的代碼來解釋我的問題。當我嘗試從第二個類發送數據時,我得到Nullreference異常代碼-1錯誤。空引用異常代碼-1當在另一個類中使用對象

我在做什麼錯?

對不起,如果這是一個愚蠢的問題。我是一個全能的程序員,這次我需要使用C#語言。

感謝您的幫助! Erik。

using Crestron.ActiveCNX; 
namespace Server 
{ 
public partial class Form1 : Form 
{ 
    public ActiveCNX cnx; 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    public void Form1_Load(object sender, EventArgs e) 
    { 
     //Initialize ActiveCNX 
     cnx = new ActiveCNX();               
     cnx.Connect("10.0.0.32", 3); 

     MethodInvoker simpleDelegate = new MethodInvoker(AsynchronousSocketListener.StartListening); 
     simpleDelegate.BeginInvoke(null, null); 
    } //Form1_Load 

    private void button2_Click(object sender, EventArgs e) 
    { 
     cnx.SendSerial(1, 1, "Hello World!"); //This works fine from this location.(sending text to a control processor). 
    } 


} //Class : Form1 
} //Namespace 

/////////////////////// ///////////////////////////////////////////////////

namespace Server 
{ 
class SendCNXUpdate 
{ 
    public void Update() 
    { 
     Form1 form1 = new Form1(); 
     //Here it usually is code to receive data from another server, parsing it and then this class is supposed to send the parsed data to the processor. 
     form1.cnx.SendSerial(1, 1, "Hello World!"); //I am using the exact same code as in the form1 class, but get the nullexception error.. 
    } 
} 
} 

回答

1

您在FormLoad方法中初始化cnx,但您需要在構造函數中執行此操作。

public Form1() 
    { 
     InitializeComponent(); 
     cnx = new ActiveCNX();               
     cnx.Connect("10.0.0.32", 3); 

    } 
1

Update()方法你不顯示的形式,讓Form_Load()方法不叫。您只能在Form_Load()中初始化cnx。你應該初始化它Update()還有:

public void Update() 
{ 
    Form1 form1 = new Form1(); 
    form1.cnx = new ActiveCNX();               
    form1.cnx.Connect("10.0.0.32", 3); 
    form1.cnx.SendSerial(1, 1, "Hello World!"); 
} 

更妙的是,你可以提取周圍CNX它所有的邏輯放到一個單獨的類從Form1脫鉤了。

相關問題