Bad practice? Non-canon usage of c#'s using statement

后端 未结 6 1799
广开言路
广开言路 2021-01-01 16:36

C# has the using statement, specifically for IDisposable objects. Presumably, any object specified in the using statement will hold some sort of re

6条回答
  •  离开以前
    2021-01-01 17:10

    I'd say it's acceptable - in fact, I've used it in some projects where I wanted to have an action triggered at the end of a specific code block.

    Wes Deyer used it in his LINQ to ASCII Art program, he called it action disposable (Wes works on the C# compiler team - I'd trust his judgment :D):

    http://blogs.msdn.com/wesdyer/archive/2007/02/23/linq-to-ascii-art.aspx

    class ActionDisposable: IDisposable
    {
        Action action;
    
        public ActionDisposable(Action action)
        {
            this.action = action;
        }
    
        #region IDisposable Members
    
        public void Dispose()
        {
            this.action();
        }
    
        #endregion
    }
    

    Now you can return that from a function, and do something like this:

    using(ExtendedConsoleWriter.Indent())
    {
         ExtendedConsoleWriter.Write("This is more indented");
    }
    
    ExtendedConsoleWriter.Write("This is less indented");
    

提交回复
热议问题