让我通过一个例子来介绍这个问题:
我们有 UserNotification 类。它包含有关通知、可能的用户选项的信息。
public class UserNotification
{
// Event fired on notification broadcast
public event EventHandler<NotifyEventArgs> Notification;
public string Title { get; set; }
public string Description { get; set; }
public List<NotificationResults> Options { get; set; }
// ...
// This function is called to raise notification
public void Notify()
{
if (Notification != null) Notification(null, new NotifyEventArgs());
}
}
所以我们有很多通知。每次当程序的某些部分需要(针对用户)发出通知时,它都会获取一些通知对象并调用 Notify() 方法。然后,Notification 事件被触发,所有监听器都可以处理此通知(将其显示在 gui 中的某个位置,显示对话框等)
最后还有来自软件不同部分甚至插件的此类通知的数量。通知监听者很可能愿意将它们全部列出。所以接下来想到的是NotificationManager。它具有 UserNotification 和 NotificationRaished 事件的集合,当任何注册的通知触发其通知事件时,该事件就会被触发
public class NotificationManager
{
public event EventHandler NotificationRaised;
private List<UserNotification> _notifications;
public void AddNotification(UserNotification notification)
{
_notifications.Add(notification);
notification.Notification += () =>
{
if (NotificationRaised != null) NotificationRaised(???, ???)
};
}
问题来了。查看NotificationRaished(???, someEventArgs)。此时,我们需要将指针传递给源通知,以便监听器可以处理此特定通知。 NotificationManager 的事件处理程序具有“源”字段,看起来与我们所需要的完全一样...问题是:
将通知指针作为源是否正确?或者根据设计和一些充分的理由,源必须是触发事件的对象?
换句话说,如果看一下这个例子,它会是“预期的行为”吗?
最佳答案
如果您要转发事件,我认为转发原始事件的源没有问题。
关于c# - 使用事件 'source' 的嵌套对象指针是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9684914/