我应该在派生的事件args类(即EventArgs.Empty)中实现null对象模式吗?如果是-什么';It’这
本文关键字:如果 模式 什么 It 对象 null args 事件 派生 实现 Empty | 更新日期: 2023-09-27 18:09:39
System.EventArgs实现了null对象模式的变体-开发人员使用EventArgs.Empty而不是null来指定"这里没有什么有趣的"情况,大概是为了减轻消费者不得不处理可能的null引用异常
我用派生的事件args类声明我自己的事件,比如ContosoEventArgs
我认为消费者能够传递类似ContosoEventArgs.Empty
的东西是很自然的(只有EventArgs.Empty
不起作用,因为这将是试图将基类的实例分配给派生类的变量(,就像他们习惯的那样。然而,这很难实现——Empty静态属性不依赖于我可以在派生类中设置的一些受保护的属性IsEmpty。如果是这样,我可以做一些类似的事情:
public class ContosoEventArgs : EventArgs
{
public static ContosoEventArgs Empty
{
get
{
return new ContosoEventArgs{IsEmpty=true};
}
}
}
干净漂亮!
然而,这样的属性并不存在,据我所知,测试EventArgs实例Empty ness的唯一方法是与EventArgs.Empty进行比较。这意味着我现在需要实现运算符==重载。。。和运算符!=,和Equals(…(,以及GetHashCode((。。。所有这些样板文件只是为了让我的专用事件参数遵循基本EventArgs 的模式
我应该只允许null吗?我认为这几乎就是他们在框架中所做的——MouseEventArgs和ImageClickEventArgs没有显示空对象模式实现的痕迹
还是我忽略了第三种选择?
我认为您可以在不重载相等成员的情况下使用此代码:
public class ContosoEventArgs : EventArgs
{
public new static readonly ContosoEventArgs Empty = new ContosoEventArgs();
}
如果您查看EventArgs,它会使用静态实例进行比较:
[ComVisible(true)]
[__DynamicallyInvokable]
[Serializable]
public class EventArgs
{
[__DynamicallyInvokable]
public static readonly EventArgs Empty = new EventArgs();
static EventArgs()
{
}
[__DynamicallyInvokable]
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public EventArgs()
{
}
}