通过 EventHandler 传回返回值 [英] Pass a return value back through an EventHandler

查看:37
本文介绍了通过 EventHandler 传回返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试写入 API,当我从表中获取数据时,我需要调用事件处理程序.像这样的:

Im trying to write to an API and I need to call an eventhandler when I get data from a table. Something like this:

    public override bool Run(Company.API api)
    {
        SomeInfo _someInfo = new SomeInfo();

        if (_someInfo.Results == 1)
            return true;
        else
            return false;

        using (MyTable table = new MyTable(api))
        {
            table.WhenData += new EventHandler<DataEventArgs<Record>>(table_WhenData);
            table.WhenDead += new EventHandler<EventArgs>(table_WhenDead);
            table.Start();
        }

    public void table_WhenData(object sender, DataEventArgs<Record> e)
    {
        return true;
    }

我遇到的问题是我不知道如何将返回值从 table_WhenData 传递回 Run 方法.

The problem that Im having is I dont know how to pass a return value back from table_WhenData to the Run method.

我尝试了很多方法(例如尝试将 _someInfo 传递给方法),但我似乎无法正确使用语法.

Ive tried many ways (like trying to pass _someInfo to the method) but I just cant seem to get the syntax right.

非常感谢任何建议.

推荐答案

这里的常见模式是不从事件处理程序返回任何数据,而是向您的事件参数对象添加属性,以便事件的使用者可以设置然后调用者可以访问的属性.这在 UI 处理代码中很常见;你到处都可以看到 Cancel 事件的概念.

The common pattern here is not to return any data from the event handler, but to add properties to your event argument object so that the consumer of the event can set the properties which the caller can then access. This is very common in UI handling code; you see the Cancel event concept all over the place.

以下是伪代码,尚未编译.它的目的是展示模式.

The following is pseudo code, and not compile ready. Its intent is to show the pattern.

public class MyEventArgs : EventArgs
{
   public bool Cancel{get;set;}
}

public bool fireEvent()
{
    MyEventArgs e=new MyEventArgs();

    //Don't forget a null check, assume this is an event
    FireEventHandler(this,e);

    return e.Cancel;
}

public HandleFireEvent(object sender, MyEventArgs e)
{
 e.Cancel=true;
}

编辑

我喜欢 Jon Skeet 的措辞:使 EventArgs 可变.也就是说,事件的使用者可以修改 EventArgs 对象的状态,从而允许事件的引发者获取该数据.

I like how Jon Skeet worded this: make the EventArgs mutuable. That is, the consumer of the event can modify the state of the EventArgs object allowing for the raiser of the event to get to that data.

这篇关于通过 EventHandler 传回返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆