gpt4 book ai didi

c# - 事件处理程序/引发程序代码片段

转载 作者:行者123 更新时间:2023-12-03 04:16:28 25 4
gpt4 key购买 nike

我想听听对以下代码片段的意见。有什么可以改进的吗?事件处理程序/引发程序的命名是否遵循最佳实践?我知道在同一个类中处理和引发事件并不是很有用,但这只是一个片段。

public class MyControl
{
public MyControl()
{
this.LogWritten += this.HandleMyControlLogWritten;
}

// Event handler
void HandleMyControlLogWritten(object sender, EventArgs e)
{
}

// Event object
public event Action<object, EventArgs> LogWritten;

// Event raiser
protected virtual void OnLogWritten(EventArgs e)
{
if (this.LogWritten != null)
{
this.LogWritten(this, e);
}
}
}

最佳答案

我建议的主要更改是获取事件处理程序的副本:

// Event raiser
protected virtual void OnLogWritten(EventArgs e)
{
var handler = this.LogWritten;
if (handler != null)
{
handler(this, e);
}
}

如果您计划(最终)在多线程场景中使用此类,这一点很重要。因此,我发现养成使用习惯是一个很好的“最佳实践”。问题是,当在多个线程中使用时,如果不创建副本,附加的唯一“处理程序”可能会在空检查和调用之间取消订阅,这将导致运行时错误。通过复制到临时变量( var handler = this.LogWritten; )行,您可以有效地创建订户列表的“快照”,然后检查它是否为空并在需要时调用。

另一个变化在于事件声明本身。而不是使用 Action<T1,T2> :

// Event object
public event Action<object, EventArgs> LogWritten;

我建议使用 EventHandler<TEventArgs> (如果您想使用自定义 EventArgs 子类)或 EventHandler (对于标准EventArgs)。这些是更多的“标准实践”,并且将是其他开发人员所期望的:

// Event object
public event EventHandler LogWritten;

关于c# - 事件处理程序/引发程序代码片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6155321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com