有了下面的代码,我认为不再需要finally块来关闭读取器或连接(如果它仍然可用的话)。使用这么多嵌套的" using“语句有什么好处或坏处?或者我应该走最后一条阻塞路线?
List<string> platforms = new List<string>();
NpgsqlDataReader reader = null;
try
{
using (NpgsqlConnection conn = new NpgsqlConnection(GetConnectionString()))
{
// Making connection with Npgsql provider
string sql = @"SELECT platforms.""name"" FROM public.""platforms""";
using (NpgsqlCommand command = new NpgsqlCommand(sql))
{
command.Connection = conn;
command.CommandType = System.Data.CommandType.Text;
conn.Open();
using (reader = command.ExecuteReader())
{
while (reader.Read())
{
platforms.Add((string)reader["name"].ToString());
}
}
}
}
}
catch (Exception err)
{
HandleError(err, "GetPlatforms");
}
finally
{
platforms = null;
if (!reader.IsClosed)
{
reader.Close();
}
}发布于 2011-04-20 21:10:07
它保证了using块完成后资源的释放。每个MSDN
using语句允许程序员指定使用资源的对象何时应该释放它们。提供给using语句的对象必须实现IDisposable接口。此接口提供Dispose方法,该方法应释放对象的资源。
using语句可以在using语句结束时退出,也可以在引发异常并且控制在语句结束前离开语句块时退出。
我看不出您在代码中列出的多个using语句块有任何错误。它确保了资源的释放,这样程序员就不会忘记。
如果您不喜欢标识,那么您可以重写它,如下所示:
using (StreamWriter w1 = File.CreateText("W1"))
using (StreamWriter w2 = File.CreateText("W2"))
{
// code here
}另请参阅nested using statements in C#上的此SO问题
发布于 2011-04-20 21:11:08
您实际上知道using get是如何编译的吗?
正在进行
using (var disposableObject = new DisposableObject())
{
// do something with it
}get编译为(或多或少):
IDisposable disposableObject = new DisposableObject();
try
{
// do something with it
}
finally
{
if (disposableObject != null)
{
disposableObject.Dispose();
}
}这只是一个想法:在哪些情况下会发生异常?
中
一个猜测:我认为NpgsqlConnection在.Dispose()本身调用.Close() --但你必须用eg验证这一点。.NET反射器
正如您通过评论所要求的那样:
catch是一个好的选择...您清楚地知道可能会出错的地方-将其拆分成几个catchesusing语句:) ...除了pt。1个发布于 2011-04-20 21:10:19
如果您使用的是" using“块,则不需要使用finally。
只需关闭读取和连接。
understanding ‘using’ block in C#
代码
使用系统;使用System.Collections.Generic;使用System.Linq;使用System.Text;
namespace BlogSamples
{
class Program
{
static void Main(string[] args)
{
using (Car myCar = new Car(1))
{
myCar.Run();
}
}
}
}代码的IL
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 37 (0x25)
.maxstack 2
.locals init ([0] class BlogSamples.Car myCar,
[1] bool CS$4$0000)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: newobj instance void BlogSamples.Car::.ctor(int32)
IL_0007: stloc.0
.try
{
IL_0008: nop
IL_0009: ldloc.0
IL_000a: callvirt instance void BlogSamples.Car::Run()
IL_000f: nop
IL_0010: nop
IL_0011: leave.s IL_0023
} // end .try
finally
{
IL_0013: ldloc.0
IL_0014: ldnull
IL_0015: ceq
IL_0017: stloc.1
IL_0018: ldloc.1
IL_0019: brtrue.s IL_0022
IL_001b: ldloc.0
IL_001c: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_0021: nop
IL_0022: endfinally
} // end handler
IL_0023: nop
IL_0024: ret
} // end of method Program::Main正如您在这里看到的,您使用的块是在try...finally中转换的。但该类必须实现IDispose接口
https://stackoverflow.com/questions/5730819
复制相似问题