哪一个更好,而当:using语句或调用Dispose()上了IDisposable在C#中?上了、而当、语句、IDisposable

2023-09-02 21:11:54 作者:落荒而逃的王

假设我有以下几点:

using(var ctx = DataContextFactory.Create(0))
{ ... Some code ... }

为什么不只是做以下而失去一对夫妇花括号:

Why not just do the following and lose a couple of curly braces?:

var ctx = DataContextFactory.Create(0);
ctx.Dispose();

谢谢你的建议!

Thanks for the advice!

推荐答案

首先是更好的。它确保即使抛出一个异常被处理,并正确地处理,其中创建(0)返回null(即不尝试调用的情况下的Dispose()上的空实例)。

The first is better. It ensures it is disposed even if an exception is thrown, and it correctly handles the case where Create(0) returns null (i.e. it doesn't attempt to call Dispose() on a null instance).