C# conditional using block statement

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

    If you repeat this pattern in many methods you can break out the pattern

    protected void OptionalNetworkCall(Action action)
    {
        if (useNetworkAccess)
        {
            using (new Core.NetworkAccess(username, password, domain))
            {
                action();
            }
        }
        else
        {
            action();
        }
    }
    
    protected void ValidateExportDirectoryExists()
    {
        OptionalNetworkCall(CheckExportDirectoryExists);
    }
    

提交回复
热议问题