11

这是一个 WinForms C# 应用程序。以下两个片段显示了初始化对象的两种不同方式。他们给出了不同的结果。

这按预期工作:

public partial class Form1 : Form
{
  private CameraWrapper cam;
  public Form1()
  {
       cam = new CameraWrapper();
       InitializeComponent();           
  }

这不起作用(详情如下):

public partial class Form1 : Form
{
  private CameraWrapper cam = new CameraWrapper();
  public Form1()
  {
       InitializeComponent();
  }

在内部CameraWrapper,我使用第三方 SDK 与相机进行通信。我在 SDK 上注册了一个事件,该事件在结果可用时被调用。

在情况 1(构造函数内部的初始化)中,一切都按预期工作,并且内部的事件处理程序CameraWrapper被调用。在情况 2 中,永远不会调用事件处理程序。

我以为这两种对象初始化风格是相同的,但似乎并非如此。为什么?

Here is the entire CameraWrapper class. The event handler should get called after a call to Trigger.

class CameraWrapper
{
    private Cognex.DataMan.SDK.DataManSystem ds;
    public CameraWrapper()
    {
        ds = new DataManSystem();
        DataManConnectionParams connectionParams = new DataManConnectionParams("10.10.191.187");
        ds.Connect(connectionParams);

        ds.DmccResponseArrived += new DataManSystem.DmccResponseArrivedEventHandler(ds_DmccResponseArrived);
    }

    public void Trigger()
    {
        SendCommand("TRIGGER ON");
    }

    void ds_DmccResponseArrived(object sender, DmccResponseArrivedEventArgs e)
    {
        System.Console.Write("Num barcodes: ");
        System.Console.WriteLine(e.Data.Length.ToString());
    }

    void SendCommand(string command)
    {
        const string cmdHeader = "||>";
        ds.SendDmcc(cmdHeader + command);
    }
}
4

1 回答 1

11

I thought that these two styles of object initialization were identical, but it seems not to be the case.

Not quite.

In the first case, the CameraWrapper constructor is called after the base class constructor for Form. In the second case, the CameraWrapper constructor is called, then the base class constructor, then the Form1 constructor body.

It's possible that something within the Form constructor affects the execution of the CameraWrapper constructor.

于 2012-10-23T17:39:03.930 回答