[英]Do I need to call .Dispose() on both of these XmlDataSource objects? “CA2000 Dispose objects before losing scope” tells me to .Dispose() it
In my extremely simplified code sample my Foo() method calls GetXmlDataSource()
which returns an XmlDataSource
. 在我的极其简化的代码示例中,我的Foo()方法调用
GetXmlDataSource()
,该方法返回一个XmlDataSource
。 CA2000 says that I should Dispose()
an XmlDatasource before losing scope. CA2000说,在丢失范围之前,我应该
Dispose()
XmlDatasource。
XmlDataSource
in a using statement? XmlDataSource
? try
/ catch
/ finally
in the lower one and a using
in the upper one? try
/ catch
/ finally
在较高的位置using
a吗? XmlDataSource
objects, one in the upper method and one in the lower method? XmlDataSource
对象,一个在上部方法中,一个在下部方法中? I'm a little fuzzy on language behavior in this one and I want to be a good boy. 我对这门语言的行为有些模糊,我想成为一个好男孩。
void Foo()
{
XmlDataSource xds = GetXmlDataSource();
}
XmlDataSource GetXmlDataSource()
{
XmlDataSource xmlDataSource = new XmlDataSource();
return xmlDataSource;
}
Should I wrap each XmlDataSource in a using statement?
是否应在using语句中包装每个XmlDataSource?
If it goes out of scope inside that method, yes, you should. 如果超出该方法的范围,则应该。 You can also use
using
on variables coming from other methods by the way. 您还可以使用
using
从由其他方式来方法变量。
Should I use try/catch/finally in the lower one?
我应该在下一个中使用try / catch / finally吗?
Yes and no. 是的,没有。 The
XmlDataSource
shouldn't be disposed since you intend to use it in the other method. 不应处置
XmlDataSource
因为您打算在其他方法中使用它。 You should dispose it if you have an exception that will prevent the variable to be passed along. 如果您有一个异常将阻止传递变量,则应处置它。
Should I use using in the upper one?
我应该在上一个使用use吗?
Yes, you should. 是的你应该。 This code will do the job.
此代码将完成工作。
using (XmlDataSource xds = GetXmlDataSource())
{ }
Do I effectively have two
XmlDataSource
objects, one in the upper method and one in the lower method?我是否有效地拥有两个
XmlDataSource
对象,一个在上部方法中,一个在下部方法中?
No, you have one. 不,你有一个。 That is why you shouldn't dispose the lower one.
这就是为什么您不应该处置下一个。 There is a reference passed from one method to another.
有一个引用从一种方法传递到另一种方法。
1) only wrap the final usage in a using. 1)仅将最终用法包装在using中。 2) no, a using is enough (note that the underlying implementation of using is a try/finally).
2)不,使用就足够了(请注意,使用的基本实现是尝试/最终实现)。 3) you have only one object instance.
3)您只有一个对象实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.