Implementing RAII in C#

前端 未结 4 1551
一整个雨季
一整个雨季 2021-01-18 00:47

I have an InfoPath form which I need to conditionally disable it\'s OnChange events. Since it\'s not possible to bind the event handlers after the form has loaded, I\'m forc

4条回答
  •  轮回少年
    2021-01-18 01:24

    In relation to question 2, it might be possible to get around it by providing a different interface to consumers of the code. Instead of providing a public class that implements IDisposable, and hoping they wrap it in a using, you could provide a static method that takes a function to execute in a "suppressed" context:

    public static class EventSuppressor {
        public void Suppress(Action action) {
            using (var s = new SuppressActions()) {
                action();
            }
        }
    
        private class SuppressActions : IDisposable {
            ...
        }
    }
    

    Then consumers can use this as follows:

    EventSuppressor.Suppress(() => {
        // OnChange events fired here are ignored
    }) // OnChange events enabled again
    

    Of course, you have to work out whether this design is appropriate, as this will result in extra function calls, compiler generated classes and closures etc.

提交回复
热议问题