C#从List <t>传递Object作为参数

时间:2017-05-27 06:31:12

标签: c#

我有一个List,我存储了一些值。我定义了一个事件,它应该弹出并将该List中的最后一个Object返回给它的EventArgs-Class-Constructor。

但是当事件被触发时,我会在此行获得System.NullException

OnID(this, new OnIDEventArgs(ID_List.Last()));

我试图将最后的ID-Object传递给OnIDEventArgs-Constructor。为什么这是NullException?

public delegate void EventHandler(object sender, OnIDEventArgs e);
public event EventHandler OnID;

IDs result = ID_List.FirstOrDefault(x => x.TID == tid_value);


    if (result != null)
       { //stuff }
    else {
       ID_List.Add(new IDs
                    {
                        TID = tid_value,
                        CENTID = centid_value,
                        IDCount = 1
                    });
       OnID(this, new OnIDEventArgs(ID_List.Last())); //System.NullException comes up here
    }

ID类

public class IDs
{
    public string TID { get; internal set; }
    public string CENTID { get; internal set; }
    public int IDCount { get; internal set; }
}

EventArgs Class

public class OnIDEventArgs : EventArgs
    {
        public string LastTID { get; private set; }
        public string LastCENTID { get; private set; }
        public int IDCount { get; private set; }
        public OnIDEventArgs(IDs result)
        {
            this.LastTID = result.TID;
            this.LastCENTID = result.CENTID;
            this.IDCount = result.IDCount;

        }
    }

1 个答案:

答案 0 :(得分:1)

这可能是由于没有订阅OnID事件,因此OnID委托为空,因此在其上调用Invoke会抛出NRE。

要避免这种情况,只需先检查OnID是否为空:

if (OnID != null) {
    OnID(this, new OnIDEventArgs(ID_List.Last()))
}

或者:

OnID?.Invoke(this, new OnIDEventArgs(ID_List.Last())