简体   繁体   English

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

[英]How to convert a try-catch-finally block to using statement in c#?

Say we create a IDisposable object, and we have a try-catch-finally block假设我们创建了一个 IDisposable 对象,并且我们有一个 try-catch-finally 块

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

How do I convert this to a using block?如何将其转换为 using 块?

If it were如果是

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

I would convert to我会转换为

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

How would I do this with the catch block?我将如何使用 catch 块做到这一点?

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

You're close.你很接近。 It's the other way around.正好相反。

In reality, the CLR doesn't have try / catch / finally .实际上,CLR 没有try / catch / finally It has try / catch , try / finally , and try / filter (that's what it does when the when clause is used on catch ).它有try / catchtry / finallytry / filter (这就是在catch上使用when子句时的作用)。 try / catch / finally in C# is just a try / catch within the try block of a try / finally . try / catch / finally在C#中仅仅是一个try / catch的中try一个块try / finally

So if you expand that and convert the try / finally to using , you get this:所以如果你扩展它并将try / finally转换为using ,你会得到这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM