有没有办法取消'IDisposable构造函数中的using语句

本文关键字:构造函数 using 语句 IDisposable 取消 有没有 | 更新日期: 2023-09-27 18:03:05

我有一个实现IDisposable的自定义类,我用它来包装代码,这样我就可以在块结束时自动运行一个函数:

class SdCardOperation : IDisposable {
    SdCardOperation() { SdCardInUse = true; }
    void Dispose() { SdCardInUse = false; }
}
using(new SdCardOperation()) {
    //do some stuff
}

(简体)

如果可能的话,我想修改我的类,以便它可以检查是否,例如,没有插入SD卡,如果是,默默地不运行using块的内容。我试着调用一个函数:

IDisposable DoSdCardOperation() {
   if(NoSdcard) return null;
   return new SdCardOperation();
}

但是即使using块接收到的IDisposable为null,它仍然运行子块。

根据我的理解,如果我在构造函数中抛出一个异常,那将"取消"using块,但我仍然需要捕获异常

有没有办法取消'IDisposable构造函数中的using语句

你不能只对using这样做,但是如果你创建一个接受Action<SdCardOperation>的函数,你可以让它有条件地运行代码。

class SdCardOperation : IDisposable
{
    /// <summary>
    /// Runs a action on the SdCardOperation only if there is a SD card available.
    /// </summary>
    /// <param name="action">The action to perform</param>
    /// <returns>True if the action was run, false if it was not.</returns>
    public static bool RunOnSdCard(Action<SdCardOperation> action)
    {
        using (var operation = new SdCardOperation())
        {
            if (operation.NoSdcard)
                return false;
            action(operation);
            return true;
        }
    }
    // Your other code here.
}

你可以这样用

bool workWasDone = SdCardOperation.RunOnSdCard((operation) =>
{
    //Do work here with operation
});
//You can check workWasDone here to see if anything was done or not.

为类添加属性bool WillRunMyExitCode

Dispose()方法中检查其值,并按此操作