How can I return an item from a special event handler

The project I'm working on requires that I can fire an event every time an item is added to the list. To do this, I created my own List class, which inherits from List, and added the OnAdd event. I also want to return an element added as EventArgs, for which I added some more code (given below):

public class ClientListObservable<Client>:List<Client> { public event EventHandler<EventArgs<Client>> OnAdd; public void Add(Client item) { if (null != OnAdd) { OnAdd(this, new EventArgs<Client>(item)); } base.Add(item); } } public class EventArgs<Client> : EventArgs { public EventArgs(Client value) { m_value = value; } private Client m_value; public Client Value { get { return m_value; } } } 

This is how I add a handler

 clientList.OnAdd += new EventHandler<EventArgs<Client>>(clientList_OnAdd); 

But in the OnAdd method:

 private void clientList_OnAdd(object sender, EventArgs e) { //want to be able to access the data members of the Client object added } 

I can access only e.Equals, e.GetHashCode, e.GetType and e.ToString and not one of the members of the Client class.

+4
source share
4 answers

Change your event arguments to:

 public class ClientEventArgs : EventArgs { public ClientEventArgs(Client value) { m_value = value; } private Client m_value; public Client Value { get { return m_value; } } } 

Then:

  private void clientList_OnAdd(object sender, ClientEventArgs e) { Client client = e.Value; } 
+6
source

Should you declare an event handler as follows:

 private void clientList_OnAdd(object sender, EventArgs<Client> e) 

?

+3
source

you should get your own class from EventArgs and have a participant to place your custom objects there, then you should trigger an event that passes such specialized EventArgs that you would create and initialize as needed.

+1
source

Create custom event arguments that extend EventArgs and have a public property of the Client object. Then add an additional custom EventArgs with the new item and return it.

+1
source

Source: https://habr.com/ru/post/1339078/


All Articles