Is using Action.Invoke considered best practice?

后端 未结 4 2021
故里飘歌
故里飘歌 2020-12-15 03:27

If I have the below code, should I just call the Action or should it call Action.Invoke?

public class ClassA
{
  public event Action OnAdd;

           


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-15 04:01

    Something I noticed on this with the latest C# 6 release as it may encourage Invoke to be used more and thought I'd add it to this old question in case it helps someone:

    "Old" way:

    Action doSomething = null; // or not null
    if (doSomething != null)
        doSomething("test");
    

    Possible pragmatic way (similar to empty event delegate pattern):

    Action doSomethingPragmatic = s => { }; // empty - might be overwritten later
    doSomethingPragmatic("test");
    

    C# 6:

    Action doSomethingCs6 = null; // or not null
    doSomethingCs6?.Invoke("test");
    
    // Not valid C#:
    // doSomethingCs6?("test")
    // doSomethingCs6?.("test")
    

提交回复
热议问题