首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在c#中将try-catch-finally块转换为using语句?

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

Stack Overflow用户
提问于 2020-02-25 07:42:49
回答 1查看 190关注 0票数 1

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

代码语言:javascript
复制
var disposable= CreateIDisposable();
try{
  // do something with the disposable.
}catch(Exception e){
  // do something with the exception
}finally{
  disposable.Dispose();
}

如何将其转换为using块?

如果是的话

代码语言:javascript
复制
var disposable= CreateIDisposable();
try{
  // do something with the disposable.
}finally{
  disposable.Dispose();
}

我会转换成

代码语言:javascript
复制
using(var disposable= CreateIDisposable()){
     // do something with the disposable.
}

我该如何使用catch块来做到这一点?

代码语言:javascript
复制
try{
  using(var disposable= CreateIDisposable()){
     // do something with the disposable.
   }
}catch(Exception e){
  // do something with the exception
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-25 07:50:32

你已经很接近了。情况正好相反。

实际上,CLR没有try/catch/finally.它有try/catchtry/finallytry/filter (这就是在catch上使用when子句时它所做的事情)。C#中的try/catch/finally只是try/catchtry块中的try/finally

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

代码语言:javascript
复制
using (var disposable = CreateIDisposable())
{
    try
    {
        // do something with the disposable.
    }
    catch (Exception e)
    {
        // do something with the exception
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60385572

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档