问题描述
如果我有以下代码,我应该调用 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 是否被认为是最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!