使用块从内部返回是否可以

编程入门 行业动态 更新时间:2024-10-25 13:30:06
本文介绍了使用块从内部返回是否可以的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

使用块从内部返回是否可以

本文发布于:2023-08-02 17:59:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1279929.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!