使用块从内部返回是否可以 [英] Is it OK doing a return from inside using block

查看:17
本文介绍了使用块从内部返回是否可以的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做代码审查,发现很多代码格式如下:

I am doing a code review, and have found alot of code with the following format:

public MyResponse MyMethod(string arg)
{
    using (Tracer myTracer = new Tracer(Constants.TraceLog))
    {
        MyResponse abc = new MyResponse();

        // Some code

        return abc;
    }
}

当我运行代码分析时,我收到 CA2000 警告 Microsoft.Reliability

When I run a code analysis I get a CA2000 warning Microsoft.Reliability

代码是否应该改写为:

public MyResponse MyMethod(string arg)
{
   MyResponse abc = new MyResponse();

   using (Tracer myTracer = new Tracer(Constants.TraceLog))
   {
       // Some code
   }
   return abc;
}

还是没关系?

编辑

报告警告的行是:

MyResponse abc = new MyResponse();

MyResponse 是标准数据集.

MyResponse is a standard Dataset.

完整的错误信息是:

警告 150 CA2000:Microsoft.Reliability:在方法xxxxx(Guid, Guid)"中,对象MyResponse"并未沿所有异常路径进行处理.在对对象MyResponse"的所有引用超出范围之前调用 System.IDisposable.Dispose.

Warning 150 CA2000 : Microsoft.Reliability : In method 'xxxxx(Guid, Guid)', object 'MyResponse ' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'MyResponse ' before all references to it are out of scope.

推荐答案

您的重写不会修复 CA2000 警告,因为问题不是 Tracer 对象,而是 MyResponse 对象.
文档指出:

Your rewrite will not fix that CA2000 warning, because the problem is not the Tracer object, but the MyResponse object.
The documentation states:

以下是 using 语句不足以保护 IDisposable 对象并可能导致 CA2000 发生的一些情况.
返回一次性对象需要在 using 块之外的 try/finally 块中构造该对象.

The following are some situations where the using statement is not enough to protect IDisposable objects and can cause CA2000 to occur.
Returning a disposable object requires that the object is constructed in a try/finally block outside a using block.

修复警告 不要弄乱你的异常的堆栈跟踪(<-点击,它是一个链接),使用这个代码:

To fix the warning without messing with the stack trace of your exceptions (<- click, it's a link), use this code:

public MyResponse MyMethod(string arg)
{
   MyResponse tmpResponse = null;
   MyResponse response = null;
   try
   {
       tmpResponse = new MyResponse();

       using (Tracer myTracer = new Tracer(Constants.TraceLog))
       {
           // Some code
       }

       response = tmpResponse;
       tmpResponse = null;
    }
    finally
    {
        if(tmpResponse != null)
            tmpResponse .Dispose();
    }
    return response;
}

为什么?请参阅链接文档中的示例.

Why? Please see the example in the linked documentation.

这篇关于使用块从内部返回是否可以的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆