【问题标题】:C# - How to react on an Event raised in another class?C# - 如何对另一个类中引发的事件做出反应?
【发布时间】:2016-11-09 14:11:32
【问题描述】:

我有 2 节课:

一个服务,它创建一个 FileSystemWatcher,当被监视的文件被 Word 保存时触发一个事件。 还有一个 UserControl,它有一些我需要在 SaveEvent 被触发时执行的功能。

如何对 UserControl 中的 SaveEvent 做出反应?

【问题讨论】:

  • 你能贴一些代码吗?
  • this
  • 如何对 UserControl 中的 SaveEvent 做出反应?您是指 Service 的 SaveEvent?

标签: c# event-handling observer-pattern


【解决方案1】:

我将在服务中创建一个事件,该事件将在引发 FileSystemWatcher 时引发。 服务应包装 FileSystemWatcher。两个对象的父对象都会调用 UserControl 上的方法。

例如:(伪)


class MyProgram
{
    Service svc;
    UserControl ctrl;

    public MyProgram()
    {
        // create the control
        ctrl = new UserControl();

        // create the service
        svc = new Service();
        svc.SaveEvent += FileChanges;

        /////// you might construct something like:   _(do not use both)_
        svc.SaveEvent += (s, e) => ctrl.FileIsSaved(e.Filename);
    }

    private void FileChanges(object sender, ServiceFileChangedEventArgs e)
    {
        ctrl.FileIsSaved(e.Filename);
    }
}

class Service
{
    // FileSystemWatcher
    private FileSystemWatcher _watcher;

    public Service() // constructor
    {
        // construct it.
        _watcher = new FileSystemWatcher();
        _watcher.Changed += Watcher_Changed;
    }

    // when the file system watcher raises an event, you could pass it thru or construct a new one, whatever you need to pass to the parent object
    private void Watcher_Changed(object source, FileSystemEventArgs e)
    {
        SaveEvent?.Invoke(this, new ServiceFileChangedEventArgs(e.FullPath)); // whatever
    }

    public event EventHandler<SaveEventEventArgs> SaveEvent;
}

class SaveEventEventArgs : EventArgs
{
    // filename etc....
}

这只是一些伪示例代码。但重要的是,您的 Program/Usercontrol 应该依赖于 FileSystemWatcher。你的Service 应该把它包起来。因此,无论何时您决定将 FileSystemWatcher 更改为(例如)DropBoxWatcher,程序的其余部分都不会损坏。

【讨论】:

    【解决方案2】:

    为该事件创建一个委托来处理它。

    myClass.SaveEvent += DelegateMethod();
    
    public void DelegateMethod(object sender, SaveEventArgs e)
    {
        //do stuff
        //run your handler code
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-17
      • 1970-01-01
      • 2015-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 2019-05-27
      相关资源
      最近更新 更多