哪一个更好,而当:using语句或调用Dispose()上了IDisposable在C#中? [英] Which is better, and when: using statement or calling Dispose() on an IDisposable in C#?

查看:249
本文介绍了哪一个更好,而当:using语句或调用Dispose()上了IDisposable在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下几点:

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).

这篇关于哪一个更好,而当:using语句或调用Dispose()上了IDisposable在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆