简体   繁体   English

返回一次性物品并获得CA2000警告

[英]Returning disposable object and getting CA2000 warning

I am trying to return XMLNodeReader to another function but getting CA2000 warning 我正在尝试将XMLNodeReader返回到另一个函数,但是收到CA2000警告

XmlNodeReader obj =new XmlNodeReader(section);
return ser.method(obj);

If I use the following code, will it work properly? 如果我使用以下代码,它将正常运行吗? The warning is supressed but not sure if it will affect the logic or not. 该警告已被禁止,但不确定是否会影响逻辑。

XmlNodeReader tempObj =new XmlNodeReader(section);
XmlNodeReader retObj=null;
retObj = tempObj;
tempObj.Dispose();
return ser.method(retObj);

Well we have no idea what ser.method does, but passing a disposed object into method seems like a bad idea to me. 好吧,我们不知道ser.method做什么,但是对我来说,将已处置的对象传递给method似乎是个坏主意。 Basically, your "fix" is bad. 基本上,您的“修复”是错误的。

There are three possibilities here (and probably others, but these are the main ones): 这里有三种可能性(可能还有其他可能性,但是这些是主要可能性):

  • ser.method disposes of its parameter itself. ser.method处理其参数。 (That's probably a bad idea, but it might do.) In that case, your original code is fine. (这可能是一个坏主意,但可能会做到。)在这种情况下,您的原始代码很好。
  • ser.method doesn't dispose of its parameter, but it returns something that relies on the reader still not being disposed ser.method不会ser.method其参数,但是会返回依赖于阅读器仍未ser.method
  • ser.method doesn't dispose of its parameter, and returns something that doesn't need the reader to stay open ser.method不会处理其参数,并且返回不需要阅读器保持打开状态的内容

I'm hoping the last of these is the case, in which case you should change your code to: 我希望情况是最后一种,在这种情况下,您应该将代码更改为:

using (XmlNodeReader reader = new XmlNodeReader(section))
{
    return ser.method(reader);
}

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

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