如何将try-catch-finally块转换为c#中的using语句?

问题描述 投票:1回答:1

假设我们创建一个IDisposable对象,并且有一个try-catch-finally块]

var disposable= CreateIDisposable();
try{
  // do something with the disposable.
}catch(Exception e){
  // do something with the exception
}finally{
  disposable.Dispose();
}

如何将其转换为using块?

如果是

var disposable= CreateIDisposable();
try{
  // do something with the disposable.
}finally{
  disposable.Dispose();
}

我会转换为

using(var disposable= CreateIDisposable()){
     // do something with the disposable.
}

我将如何使用catch块?

try{
  using(var disposable= CreateIDisposable()){
     // do something with the disposable.
   }
}catch(Exception e){
  // do something with the exception
}
c# try-catch using try-catch-finally
1个回答
3
投票

您接近。反过来。

实际上,CLR没有try /catch/ finally。它具有try / catchtry / finallytry / filter(这是在when上使用catch子句时的操作)。 C#中的try /catch/ finally只是try / catchtry块内的try / finally

因此,如果将其展开并将try / finally转换为using,则会得到以下信息:

using (var disposable = CreateIDisposable())
{
    try
    {
        // do something with the disposable.
    }
    catch (Exception e)
    {
        // do something with the exception
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.