假设我们创建一个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
}
您接近。反过来。
实际上,CLR没有try
/catch
/ finally
。它具有try
/ catch
,try
/ finally
和try
/ filter
(这是在when
上使用catch
子句时的操作)。 C#中的try
/catch
/ finally
只是try
/ catch
的try
块内的try
/ finally
。
因此,如果将其展开并将try
/ finally
转换为using
,则会得到以下信息:
using (var disposable = CreateIDisposable())
{
try
{
// do something with the disposable.
}
catch (Exception e)
{
// do something with the exception
}
}