通常我们使用此代码:
private EventHandler _updateErrorIcons;
public event EventHandler UpdateErrorIcons
{
add { _updateErrorIcons += value; }
remove { _updateErrorIcons -= value; }
}
Run Code Online (Sandbox Code Playgroud)
是否有与自动属性类似的快捷方式?就像是:
public event EventHandler UpdateErrorIcons { add; remove; }
Run Code Online (Sandbox Code Playgroud)
Dan*_*Tao 15
是的.摆脱{ add; remove; }部分和支持代表字段,你是金色的:
public event EventHandler UpdateErrorIcons;
Run Code Online (Sandbox Code Playgroud)
而已!
在您提出这个问题之前,我先补充一下,我甚至没想过事件的自动实现版本与属性的事件不一致.就个人而言,如果自动实现的事件按照您在问题中首次尝试的方式工作,我实际上更喜欢它.这将是更加一致,同时也将作为一种心理提醒的事件是不相同的委托领域,就像性质是不相同的常规领域.
老实说,我认为你是罕见的例外,你其实知道有关自定义语法第一.很多.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.
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,上述内容利用无锁同步来有效地序列化add和remove调用.因此,如果您使用最新的C#编译器,即使是同步也不需要实现add/ remove自己.
public event EventHandler UpdateErrorIcons;
Run Code Online (Sandbox Code Playgroud)
很好
您可以使用
yourObbject.UpdateErrorIcons += YourFunction;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1684 次 |
| 最近记录: |