简体   繁体   中英

C# NullReferenceException while EventHandler

I get a NullRefernceException even though I subscribed to the event in an Start Methode.

Where I create my Event:

public EventHandler<CustomArgs> ClickEvent;

    private void OnMouseDown()
    {
        Debug.Log("Clicked");
        CustomArgs args = new CustomArgs();
        args.Name = gebäude.ToString();
        args.Level = Level;
        args.MenuePosition = Menue;

        ClickEvent?.Invoke(this, args);
    }

Where I subscribe to my Event:

private void Start()
    {
        miene.ClickEvent += ClickEvent;
        Debug.Log("Event Addedet");
    }

    private void ClickEvent(object sender, CustomArgs e)
    {
        //some useless stuff 
    }

Events are null when no-one has subscribed. Fortunately, modern C# makes this easy:

ClickEvent?.Invoke(this, args);

With older language versions, you need to be more verbose:

var handler = ClickEvent;
if (handler != null) handler(this, args);

They mean exactly the same thing.

As a small optimisation, you may wish to defer creating the CustomArgs object until you know someone cares, though:

ClickEvent?.Invoke(this, new CustomArgs {
    Name = gebäude.ToString(),
    Level = Level,
    MenuePosition = Menue
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM