using语句C# [英] C# using statement
问题描述
我真的很想得到这个我的头了。请看下面的代码:
I really want to get this out of my head. Please see below code:
using (DataTable resultTable = DBUtility.GetSingleDBTableResult(connectionString, "SELECT * FROM MyDBTable")) {
List<string> resultsList = new List<string>();
foreach (DataRow dataRow in resultTable.Rows) {
resultsList.Add(dataRow[0].ToString());
}
return resultsList;
}
是数据表处置?有人能解释这是怎么翻译成一个try / catch / finally块? ?MSDN指出,如果发生异常,Dispose方法仍然会被调用,但怎么样return语句
Is the datatable disposed? Can someone explain how this is translated to a try/catch/finally block? MSDN states that if an exception occurred, the Dispose method will still be called but what about the return statement?
或者我应该使用下面的代码:
Or should i just use below code:
List<string> resultsList = new List<string>();
using (DataTable resultTable = DBUtility.GetSingleDBTableResult(connectionString, "SELECT * FROM MyDBTable")) {
foreach (DataRow dataRow in resultTable.Rows) {
resultsList.Add(dataRow[0].ToString());
}
}
return resultsList;
也许,第二个应该被使用,但我只需要启蒙:)。请解释。谢谢你。
Probably, the second one should be used but I just need enlightenment :). Please explain. Thanks.
推荐答案
使用
语句只是语法糖,它被翻译进入try / finally块。与您的代码开始,这里的C#编译器将如何翻译使用
块进入try / finally块。
using
statement is just syntactic sugar and it gets translated into try/finally block. Starting with your code, here's how the C# compiler will translate the using
block into try/finally block.
try
{
DataTable resultTable = DBUtility.GetSingleDBTableResult(connectionString, "SELECT * FROM MyDBTable");
List<string> resultsList = new List<string>();
foreach (DataRow dataRow in resultTable.Rows)
{
resultsList.Add(dataRow[0].ToString());
}
return resultsList;
}
finally
{
resultTable.Dispose();
}
你可以从代码中看到,resultTable得到处理肯定不管return语句。在使用块仅可以确保对象被范围后处理。
As you can see from the code, the resultTable gets disposed for sure regardless of the return statement. The using block only makes sure that object gets disposed after the scope.
您的第一个代码看起来不错,我和不需要改变。
Your first code looks ok to me and need not be changed.
这篇关于using语句C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!