通常我们使用此代码:
private EventHandler _updateErrorIcons;
public event EventHandler UpdateErrorIcons
{
add { _updateErrorIcons += value; }
remove { _updateErrorIcons -= value; }
}
是否有类似自动属性的快捷方式? 像这样的东西:
public event EventHandler UpdateErrorIcons { add; remove; }
最佳答案
是的。去掉 { 添加;去掉; }
部分和支持委托(delegate)字段,你就成功了:
public event EventHandler UpdateErrorIcons;
就是这样!
我补充一点,在你问这个问题之前,我什至没有想过事件的自动实现版本与属性的版本不一致。就个人而言,如果自动执行的事件按照您在问题中首次尝试的方式工作,我实际上更喜欢它。它会更加一致,并且它还可以作为一种心理提醒,即事件不与委托(delegate)字段相同,就像属性与常规字段不同一样。
老实说,我认为您是首先真正了解自定义语法的罕见异常(exception)。许多 .NET 开发人员根本不知道有一个选项可以实现您自己的 add
和 remove
方法。
更新:为了您的安心,我已经确认使用Reflector C# 4 中事件的默认实现(即当您使用自动实现的路由时生成的实现)等同于此:
private EventHandler _updateErrorIcons;
public event EventHandler UpdateErrorIcons
{
add
{
EventHandler current, original;
do
{
original = _updateErrorIcons;
EventHandler updated = (EventHandler)Delegate.Combine(original, value);
current = Interlocked.CompareExchange(ref _updateErrorIcons, updated, original);
}
while (current != original);
}
remove
{
// Same deal, only with Delegate.Remove instead of Delegate.Combine.
}
}
请注意,上面利用无锁同步有效地序列化 add
和 remove
调用。因此,如果您使用的是最新的 C# 编译器,则无需为同步甚至自己实现add
/remove
。
关于c# - 编写事件的简短方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4959797/