在using语句中使用return

4 篇文章 0 订阅
asp.net中的using语句有两个场合使用:
1、引用命名空间;
2、定义一个范围,将在此范围之外释放一个或多个对象。
这里我们说的是第二种情形。
using是可以同时声明多个对象的,例如:
using(DataSet ds1 = new DataSet(),ds2 = new DataSet()){}
在using语句中使用return语句返回值时,using仍然能够保证释放指定的对象。不但如此,不管是正常程序流结束、使用return语句跳出还是抛出异常,using范围内的对象都会正常析构。在这一点上有点类似于finally,不过比finally更为及时,因为无需等待垃圾回收机制启动的时刻,而是在退出using语句时启动!
参考一下下面一段文字:
Return Within a C# Using Statement 
While writing some code earlier today I needed to return from within a using statement. Doing these sorts of things always makes me appreciate the using statement and how wonderful it really is, so I decided to write about it here. As many of you know the using statement in C# is a good tool for managing types which will be accessing unmanaged resources. Some examples of these are SqlConnections, FileReaders, and plenty of other similar types. The key to these is that they all implement the IDisposable interface. This means that they all need to be cleaned up carefully after using them.
The using statement is great because it guarantees that the declared object is disposed no matter how the execution completes. Whether you reach the end curly brace marking the end of the using statement, throw and exception, or return from a function, the using statement will call the dispose method and clean up the object.
This was important in my code because I was able to return directly from within the using statement without worrying about whether or not eh dispose method will fire. Whenever I use an object which accesses unmanaged resources I always always always put it in a using statement.
It is very important to use a using statement, because it will give you this guarantee that the object will be disposed of correctly. The object's scope will be for the extent of the using statement, and during the scope of the object it will be read-only if defined in the using statement. This is also very nice, because it will prevent this important object which manages the unmanaged from being modified or reassigned.
This is safe to do, because of how great the using statement is. No matter which return we hit we know the XmlReader will be disposed of correctly.

using (XmlReader reader = XmlReader.Create(xmlPath)){ // ... Do some work... if (someCase) return 0; // ... Do some work... if (someOtherCase) return 1;}return -1;Happy coding. Enjoy this powerful tool.

参考文章:http://aspadvice.com/blogs/name/archive/2008/05/22/Return-Within-a-C_2300_-Using-Statement.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值