对象引用未设置为事件处理程序上的对象实例

时间:2017-07-20 06:55:54

标签: c#

我收到消息“对象引用未设置为对象的实例”。在这行代码上: LaneControllerLane(this, EventArgs.Empty);

这是整个计划:

的MainForm

public static event EventHandler LaneControllerDevice;
public static event EventHandler LaneControllerLane;
internal void LaneMessage(string message)
    {

        CommonEntitiesForTollApps.LANE = message.Split('|')[0];
        CommonEntitiesForTollApps.DEVICE = message.Split('|')[1];

        pnlForControl.BeginInvoke(new Action(() =>
        {
            LaneControllerLane(this, EventArgs.Empty);
        }));
    }

ControlForm

private void ctrlLane_Load(object sender, EventArgs e)
        {

            MainForm.LaneControllerDevice += new EventHandler(CheckSignal);
            MainForm.LaneControllerLane += new EventHandler(CheckLaneOperation);

        }

private void CheckLaneOperation(object sender, EventArgs e)
    {
        if(CommonEntitiesForTollApps.LANE == this.LaneName)
        {
            switch (DEVICE)
            {
                case "Scanner":
                    lblScanner.Text = "1";
                    break;
                case "Printer":
                    lblPrinter.Text = "1";
                    break;
                case "RFID":
                    lblTransactionType.Text = CommonEntitiesForTollApps.TRANSACTION_TYPE;
                    break;
            }
        }
        else
        {
            return;
        }
    }

你能指出我做错了什么吗?谢谢。

1 个答案:

答案 0 :(得分:1)

替换

LaneControllerLane(this, EventArgs.Empty);

LaneControllerLane?.Invoke(this, EventArgs.Empty);

这是你发射事件的方式。 ?是空检查的缩写形式:null conditional operators

如果您使用的是较旧的框架,则必须使用

if(LaneControllerLane != null)
{
    LaneControllerLane.Invoke(this, EventArgs.Empty);
}

代替。