C# 在另一个类中使用对象时,Nullreference异常代码-1

C# 在另一个类中使用对象时,Nullreference异常代码-1,c#,C#,如果我的标题问题文本不正确,我道歉。。。 我的问题是: 发布在下面的第一个类运行良好,我可以通过Crestron.ActiveCNX将数据发送到控制处理器。显示的包含“Hello world”的行将数据发送到控制处理器,在这里它可以正常工作。在同一个类中,我启动ActiveCNX通信,还有事件处理(此处未显示)。 但我有很多代码,需要从另一个类通过同一个ActiveCNX连接发送数据。这个类显示了必要的代码来解释我的问题。当我尝试从第二个类发送数据时,我得到了Nullreference异常代码-

如果我的标题问题文本不正确,我道歉。。。 我的问题是: 发布在下面的第一个类运行良好,我可以通过Crestron.ActiveCNX将数据发送到控制处理器。显示的包含“Hello world”的行将数据发送到控制处理器,在这里它可以正常工作。在同一个类中,我启动ActiveCNX通信,还有事件处理(此处未显示)。 但我有很多代码,需要从另一个类通过同一个ActiveCNX连接发送数据。这个类显示了必要的代码来解释我的问题。当我尝试从第二个类发送数据时,我得到了Nullreference异常代码-1错误

我做错了什么

对不起,如果这是一个愚蠢的问题。我是一个全能的程序员,这次我需要使用C语言

谢谢你的帮助! 埃里克

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

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..
    }
} 
}

在FormLoad方法中初始化cnx,但需要在构造函数中进行初始化

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

    }
Update()
方法中,您不显示表单,因此不会调用
form\u 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 it周围的所有逻辑提取到一个单独的类中,以将其与
Form1
解耦

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!");
}