Is using Action.Invoke considered best practice?(使用 Action.Invoke 是否被认为是最佳实践?)
问题描述
如果我有以下代码,我应该调用 Action 还是调用 Action.Invoke?
If I have the below code, should I just call the Action or should it call Action.Invoke?
public class ClassA
{
public event Action<string> OnAdd;
private void SomethingHappened()
{
if (OnAdd != null)
OnAdd("It Happened"); //Should it be OnAdd.Invoke("It Happened") ???????
}
}
public class ClassB
{
public ClassB()
{
var myClass = new ClassA();
myClass.OnAdd += Add;
}
private void Add(string Input)
{
//do something
}
}
推荐答案
两者是等价的,编译器将OnAdd("It Happened");
转换成OnAdd.Invoke("It发生了");
为您服务.
The two are equivalent, the compiler converts OnAdd("It Happened");
into OnAdd.Invoke("It Happened");
for you.
我想这是一个偏好问题,但我个人更喜欢简洁的形式.
I guess it's a matter of preference, however I personally prefer the terser form.
顺便说一句,通常最好在调用类级别委托之前获取类级别委托的本地副本以避免竞争条件,即 OnAdd
在检查时不为空,但是在它被调用的时候:
As an aside, it is generally preferable to take a local copy of a class level delegate before invoking it to avoid a race condition whereby OnAdd
is not null at the time that it is checked, but is at the time that it is invoked:
private void SomethingHappened()
{
Action<string> local = OnAdd;
if (local != null)
{
local("It Happened");
}
}
这篇关于使用 Action.Invoke 是否被认为是最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Action.Invoke 是否被认为是最佳实践?


基础教程推荐
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01