假设我们创建了一个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
}发布于 2020-02-25 07:50:32
你已经很接近了。情况正好相反。
实际上,CLR没有try/catch/finally.它有try/catch、try/finally和try/filter (这就是在catch上使用when子句时它所做的事情)。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
}
}https://stackoverflow.com/questions/60385572
复制相似问题