如何从自定义事件处理程序返回项目
我正在从事的一个项目要求我能够在每次将项目添加到列表时触发一个事件。为了实现这一点,我创建了一个继承自 List 的自定义 List 类,并添加了 OnAdd 事件。我还想返回作为 EventArgs 添加的项目,为此我添加了更多代码(如下所示):
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; }
}
}
这就是我添加处理程序的方式
clientList.OnAdd += new EventHandler<EventArgs<Client>>(clientList_OnAdd);
但是,在 OnAdd 方法中:
private void clientList_OnAdd(object sender, EventArgs e)
{
//want to be able to access the data members of the Client object added
}
我只能访问 e.Equals、e.GetHashCode、e .GetType 和 e.ToString,并且没有 Client 类的成员。
A project I'm working on requires me to be able to fire off an event everytime an item is added to a list. To achieve this, I created a custom List class inheriting from List and added a OnAdd event. I also want to return the item being 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 only access e.Equals, e.GetHashCode, e.GetType and e.ToString, and none of the members of Client class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将您的事件参数更改为:
然后:
Change your event args to:
Then:
您的事件处理程序不应该像这样声明吗:
?
Shouldn't your event handler be declared like this:
?
您应该从 EventArgs 派生您的自定义类,并有一个成员在其中托管您的自定义对象,然后您应该调用传递此类您将根据需要创建和初始化的专用 EventArgs 的事件。
you should derive your custom class from EventArgs and have a member to host your custom objects in there, then you should invoke the event passing such specialized EventArgs which you would have created and initialized as needed.
创建您自己的事件参数,该事件参数扩展 EventArgs 并具有“Client”对象的公共属性。然后在添加时使用新项目填充自定义 EventArgs 并返回它。
Create your own event args that extends EventArgs and has a public property of a "Client" object. Then on add populate the custom EventArgs with the new item and return it.