C# conditional using block statement

后端 未结 10 1667
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  • One option, which is somewhat nasty but would work, based on the fact that the C# compiler calls Dispose only if the resource is non-null:

    protected void ValidateExportDirectoryExists()
    {
        using (useNetworkAccess 
                   ? new Core.NetworkAccess(username, password, domain)
                   : null)
        {
            CheckExportDirectoryExists();
        }
    }
    

    Another alternative would be to write a static method which returned either null or a NetworkAccess:

    private Core.NetworkAccess CreateNetworkAccessIfNecessary()
    {
        return useNetworkAccess
            ? new Core.NetworkAccess(username, password, domain)) : null;
    }
    

    Then:

    protected void ValidateExportDirectoryExists()
    {
        using (CreateNetworkAccessIfNecessary())
        {
            CheckExportDirectoryExists();
        }
    }
    

    Again, I'm still not sure I don't prefer the original... it really depends on how often you need this pattern.

    0 讨论(0)
  • 2021-02-02 08:00

    using scope will only dispose a object if the class implements IDisposible interface so yes you need to implement dispose method.

    0 讨论(0)
  • 2021-02-02 08:10
    protected void ValidateExportDirectoryExists()
    {
          var access = useNetworkAccess
              ? new Core.NetworkAccess(username, password, domain)
                : null;
    
          using (access)
          {
              CheckExportDirectoryExists();
          }
    }
    
    0 讨论(0)
  • 2021-02-02 08:12

    Whatever is enclosed within the using statement will have it's IDispoable.Dispose called as dictated by the IDisposable interface. As seen on MSDN for using...

    Provides a convenient syntax that ensures the correct use of IDisposable objects.

    Therefore if you put a custom type within the using statement it should clean up its resources appropriately via the IDisposable interface.

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