另一个类中的方法在调用类时调用一个事件?

Phi*_*hil 2 c# events delegates windows-phone-7

我需要开始下载一些html,所以我在另一个类中调用void GetHTML.当它完成后,我想传递它应该在调用类中引发的事件.我怎么能这样做?

所以它看起来像这样:

public class Stuff
{
    public void GetHTML(string url, event to raise here)
    {
       //Do stuff then raise event
    }
}
public class Other
{
    public Other()
    {
        Stuff stuff = new Stuff();
        stuff.GetHTML(someUrl, somehow sending info that HTML_Done should be called);
    }
    void HTML_Done(string result, Event e)
    {
         //Do stuff with the result since it's done
    }
}
Run Code Online (Sandbox Code Playgroud)

我意识到我不清楚我想做什么,我很乐意填写任何遗漏的部分.

谢谢你的任何建议!

Nop*_*ope 12

事件订阅和通知

public class Stuff
{
    // Public Event to allow other classes to subscribe to.
    public event EventHandler GetHtmlDone = delegate { };

    public void GetHTML(string url)
    {
        //Do stuff

        // Raise Event, which triggers all method subscribed to it!
        this.GetHtmlDone(this, new EventArgs());
    }
}

public class Other
{
    public Other()
    {
        Stuff stuff = new Stuff();

        // Subscribe to the event.
        stuff.GetHtmlDone += new EventHandler(OnGetHtmlDone);

        // Execute
        stuff.GetHTML("someUrl");
    }

    void OnGetHtmlDone(object sender, EventArgs e)
    {
        //Do stuff with the result since it's done
    }
}
Run Code Online (Sandbox Code Playgroud)

使用此模式可以允许更多订阅者.

您也不会将通知程序和Stuff类绑定到调用者Other类.

你有没有订阅者,没有订阅,没有差异Stuff.

Stuff类不应该知道的用户,它应该仅仅提高它公开认购的事件.

编辑
正如ctacke在评论中正确指出的那样,this.GetHtmlDone(this, new EventArgs());如果没有人订阅,提升事件将导致异常.
我更改了上面的代码,以确保通过初始化我的事件处理程序来始终安全地引发事件.
因为我一直在使用它(通过提高它)我确信始终初始化你正在使用的东西是一个好习惯.

我可以在事件处理程序上添加一个空检查,但在我个人意见中,我不同意必须由stuff该类负责.我觉得应该总是提出这个事件,因为它是"负责任"的事情.

我发现这个帖子在SO上向我证实这样做似乎没有错.

此外,我还对该代码运行代码分析,以确保我没有通过初始化EventHandler来破坏CA1805规则.没有引发CA1805并且没有违反任何规则.

从评论中使用我的汽车比喻,我认为不会初始化事件处理程序并一直提高它会比说"当你在车里转弯时只使用你的指示器,如果有人在看,如果没有不打扰" .你永远不知道是否有人在看,所以你不妨确保你总是这样做.

这只是我个人的偏好.如果您喜欢这样做,请随时添加!= null检查.

非常感谢ctacke的评论,并指出了这一点.我从中学到了很多东西.
我现在必须回到我的一些项目并更新一些代码,以确保如果没有人订阅我的事件,我的库就不会崩溃.在任何测试中,我都感觉很傻.


dev*_*tal 5

我不确定这是否是您所追求的,但您可以使用内置的Action委托类型:

public class Stuff
{
  public void GetHTML(string url, Action<string, Event> callback)
  {
     //Do stuff 

     //raise event
     callback("result here", new Event());       
  }
}

stuff.GetHTML(someUrl, HTML_Done);
Run Code Online (Sandbox Code Playgroud)

或者,使用标准事件模式EventHandler<T>委托类型.您需要创建自己的EventArgs类型.