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 是否被认为是最佳实践?
基础教程推荐
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
