C# conditional using block statement

后端 未结 10 1694
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-02 07:25

I have the follow code but it is awkward. How could I better structure it? Do I have to make my consuming class implement IDisposable and conditionally construct the network acc

10条回答
  •  有刺的猬
    2021-02-02 07:46

    The using statement is a shortcut to avoid "finally" blocks and should only be used when it makes the code easier to follow. In your case I would write the following code. It may not be as brief as some of the other versions, but is much more straight forward.

    protected void ValidateExportDirectoryExists()
    {
        Core.NetworkAccess access = useNetworkAccess ? new Core.NetworkAccess(username, password, domain) : null;    
    
        try
        {
            CheckExportDirectoryExists()
        }
        finally
        {
           if (access != null)
           {
               access.Dispose();
           }
        }
    }
    

提交回复
热议问题