c# - 事件集锦

标签 c# .net events collections

我在 C# 中使用事件作为发布者/订阅者模式。然而,我在设计时并不知道我的程序将使用多少发布者。我想直接将事件动态添加到类中,或者更合理地添加到包含事件的集合/字典中。

使用 C# 是否可以实现这些场景?

最佳答案

创建一个您的发布者向其发布并且您的订阅者订阅的调解器。例如:

public class Mediator
{
    public static readonly Mediator Current = new Mediator();
    public event EventHandler<EventArgs> EventRaised;
    public void RaiseEvent(object sender, EventArgs eventArgs)
    {
        if (EventRaised!=null) 
            EventRaised(sender, eventArgs);
    }
}
public class PublisherEventArgs : EventArgs
{
    public string SomeData { get; set; }
}
public class Publisher
{
    public void Publish(string data)
    {
        Mediator.Current.RaiseEvent(this, new PublisherEventArgs() { SomeData = data} );
    }
}
public class Subscriber
{
    public Subscriber()
    {
        Mediator.Current.EventRaised += HandlePublishedEvent;
    }

    private void HandlePublishedEvent(object sender, EventArgs e)
    {
        if(e is PublisherEventArgs)
        {
            string data = ((PublisherEventArgs)e).SomeData;
            // todo: do something here
        }
    }
}

确保在订阅者上实现 IDisposable(在我的示例中不是),以便它在处置期间取消订阅调解器。

关于c# - 事件集锦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7245592/

相关文章:

c# - c#中的多个事件

C# ListView with CheckBoxes,多选行时自动选中复选框

c# - 使用 MVVM 跨多个子控件的 WPF UserControl 自定义粘贴命令

.net - 为什么要使用 Assert.ReplaceNullChars(string input)?

c# - Entity Framework 有时不加载子对象/集合的内容

c# - DownloadStringCompletedEventHandler 参数

c# - LINQ to SQL - 具有多个连接条件的左外连接

c# - 打破单线程

c# - LINQ 查询子句的顺序是否会影响 Entity Framework 的性能?

python - 使用卷挂载的Docker上的事件监听器不起作用