C#使用清除处置
我正在复习一些C#代码,我已经有一段时间没有使用C#了,所以我想确定我的直觉是正确的。在这段代码中,我看到在using块中有许多地方执行了如下操作:C#使用清除处置,c#,dispose,using,C#,Dispose,Using,我正在复习一些C#代码,我已经有一段时间没有使用C#了,所以我想确定我的直觉是正确的。在这段代码中,我看到在using块中有许多地方执行了如下操作: using(StreamWriter thing = new StreamWriter()) { DataSet DS = SQLQueryMethod(); do stuff to DS and log that stuff to the a log file using thingy... DS.clear();
using(StreamWriter thing = new StreamWriter()) {
DataSet DS = SQLQueryMethod();
do stuff to DS and log that stuff to the a log file using thingy...
DS.clear();
DS.Dispose();
}
现在,我已经对此做了一些研究,并且回顾了几年来我记忆的衰退,我认为有很多方法可以更好地做到这一点。我想知道哪一种方式更“标准”/“最佳”呢。我认为下面的第一条是最好的方法
提前谢谢
using(StreamWriter thing = new StreamWriter(), DataSet DS = new DataSet()) {
DS = SQLQueryMethod()
do stuff to DS{...}
}
using (StreamWriter thing = new StreamWriter())
using (DataSet DS = new DataSet())
{
DS = SQLQueryMethod();
//do stuff ....
}
因为StreamWriter和DataSet在IDisposable接口中实现了所需的Dispose()方法,所以无需在后面显式调用它正确的方法是处理实现IDisposable的所有内容,如
using (var thing = new StreamWriter())
using (var ds = SQLQueryMethod())
{
do stuff to DS {}
}
其他建议的答案是错误的
using(StreamWriter thing = new StreamWriter())
using(DataSet DS = new DataSet())
{
// this won't compile - DS is in using so it is a read-only variable
DS = SQLQueryMethod()
do stuff to DS{...}
}
参考资料:这个问题可能属于,但要回答你的问题是的,是的,是的,但我仍然认为你需要使用两个单独的变量,只要我在实例化同一对象的方法中看到
.Dispose()
,我总是畏缩不前,想看看如何用using
模式重写它,这几乎一直都很简单。我看到多个using语句的多个答案,而不是将多个项目添加到一个using语句中,它们之间有什么区别吗?示例:using(itemA,itemB){}vs using(itemA)using(itemB){}由于您在using中,从技术上讲,您不必调用dispose,但是如果您想使用using((IDisposable)DS.dispose()中的一行代码来处理数据集,您可以在using中对数据集执行类似的操作代码>我参考了下面关于using语句的Microsoft链接,其中显示了一个using语句,其中包含以逗号分隔的项目列表。第三个codebloc示例:OK,未完全阅读它。它表示一个类型的多个实例,所以我猜每个不同类型都有多个语句。我的错。如果您想保存一行,您甚至可以使用(DataSet DS=SQLQueryMethod())
执行,为什么每个人都在回答中声明一个新DataSet()
?using
语句不是保留了原始引用吗?@flkes-我也不明白-这不会编译:)@OndrejSvejdar那么为什么这么多人投票?奇怪的是,这个问题是关于使用usings和IDisposable的。