C# conditional using block statement

后端 未结 10 1681
佛祖请我去吃肉
佛祖请我去吃肉 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:45

    I don't know if it is "better", but you could use the null object pattern and have a "null" disposable network access object. Something like this:

    protected void ValidateExportDirectoryExists()     
    {
      using (GetNetworkAccess(username, password, domain))
      {                 
        CheckExportDirectoryExists();
      }
    } 
    
    protected IDisposable GetNetworkAccess(string username, string password, string domain)
    {
      return useNetworkAccess ? new Core.NetworkAccess(username, password, domain) : new NullNetworkAccess(username, password, domain);
    }
    
    internal class NullNetworkAccess : IDisposable
    {
      internal NullNetworkAccess(string username, string password, string domain)
      {
      }
    
      public void Dispose()
      {
      }
    }
    

    This is probably too cute for its own good.

    [EDIT] Just saw in Jon's answer that null can be used in a using statement. I had no idea!

提交回复
热议问题