Is it OK doing a return from inside using block(使用块从内部返回是否可以)
问题描述
我正在做代码审查,发现很多代码格式如下:
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.
这篇关于使用块从内部返回是否可以的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用块从内部返回是否可以
- 如何用自己压缩一个 IEnumerable 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04