.NET Framework supported empty action syntax or singleton

前端 未结 1 1564
情歌与酒
情歌与酒 2021-01-22 10:25

When working with existing frameworks, sometimes you need to pass in an action delegate which performs no action usually an extension point added by the original developer. Exam

相关标签:
1条回答
  • 2021-01-22 11:01

    There's nothing built-in that I'm aware of.

    You could just define the delegate once as a helper singleton:

    var anObject = new Foo(NoOpAction.Instance);
    
    // ...
    
    var anotherObject = new Bar(NoOpAction.Instance);
    
    // ...
    
    public static class NoOpAction
    {
        private static readonly Action _instance = () => {};
    
        public static Action Instance
        {
            get { return _instance; }
        }
    }
    

    And because you're handed exactly the same delegate every time you use NoOpAction.Instance throughout your program, you're also saving on the (admittedly small) cost of creating and garbage-collecting multiple delegates that all do the same thing.

    0 讨论(0)
提交回复
热议问题