我查阅了档案,发现有很多关于发送方是什么以及为什么应该使用该模式的问题,但我没有看到有关自定义事件和发送方类型的内容。
假设我正在创建一个名为Subscription的自定义类,它实现了ISubscription接口,并且我有一些名为SubscriptionEventArgs的事件参数。如果Subscription有一个名为Changed的事件,那么Changed(ISubscription sender, SubscriptionEventArgs e)的事件签名有什么问题吗?
下面是一些代码以帮助理解问题:
public class SubscriptionEventArgs : EventArgs
{
// guts of event args go here
}
public interface ISubscription
{
event Action<ISubscription, SubscriptionEventArgs> Changed;
}
public class Subscription : ISubscription
{
public event Action<ISubscription, SubscriptionEventArgs> Changed;
private void OnChanged(SubscriptionEventArgs e)
{
if (Changed!= null)
{
Changed(this, e);
}
}
}
如果您不喜欢使用动作而是想要使用“EventHandler”,那么您可以使用自定义的通用“EventHandler”来完成相同的事情。
public delegate void EventHandler<TSender, TEventArgs>(TSender sender, TEventArgs e);
public class SubscriptionEventArgs : EventArgs
{
// guts of event args go here
}
public interface ISubscription
{
event EventHandler<ISubscription, SubscriptionEventArgs> Changed;
}
public class Subscription : ISubscription
{
public event EventHandler<ISubscription, SubscriptionEventArgs> Changed;
private void OnChanged(SubscriptionEventArgs e)
{
if (Changed!= null)
{
Changed(this, e);
}
}
}
作为对Hans请求示例事件处理程序的回应:
public class SubscriptionCollection
{
// what is actually holding the subscriptions is not really relevant to the question
private List<ISubscription> _subscriptions;
public SubscriptionCollection()
{
_subscriptions = new List<ISubscription>();
}
public void Add(ISubscription subscription)
{
subscription.Changed += new EventHandler<ISubscription, SubscriptionEventArgs>(Subscription_Changed);
_subscriptions.Add(subscription);
}
private void Subscription_Changed(ISubscription sender, SubscriptionEventArgs e)
{
// Now when the subscription changed event is being handled by the collection
// I don't have to look up the subscription in the list by some key and I don't
// have to cast sender to the correct type because the event handler was typed
// correctly from the beginning.
}
}
在列表中查找订阅似乎是微不足道的,但如果我正在处理庞大的数据集,并且新的数据量通过实时流传入应用程序,那么停下来从列表中获取引用或执行转换步骤的成本就没有意义了。他们在2.0中给我们提供了泛型以解决这个问题,所以我不明白为什么我们没有得到一个通用的事件处理程序,这使我开始质疑通用事件处理程序有什么问题。