我从Using语句返回的对象会发生什么? [英] What happens to an object I'm returning from a Using statement?

查看:74
本文介绍了我从Using语句返回的对象会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用(MemoryStream ms = new MemoryStream)考虑此代码段

Consider this code snippet

using(MemoryStream ms = new MemoryStream())
{
     //code
     return ms;
}

ms会被处理掉吗?如果确实如此,何时?

Will ms get disposed? And if it does, when?

推荐答案

在返回项目之前将调用Dispose,因此返回的项目不太可能有用,但它取决于实现实际的班级。在大多数情况下,对项目的任何访问都应该导致ObjectDisposedException。



不要在<$ c $的范围之外返回或以其他方式使用该项目c>使用块。



Dispose will be called before the item is returned, therefore the returned item is unlikely to be useful, but it depends on the implementation of the actual class. In most cases, any access to the item should result in an ObjectDisposedException.

Don't return or otherwise make the item available outside the confines of the using block.

public X x ;

using ( X y = new X() ) { x = y } ;





同样糟糕。



Is just as bad.


此代码

This code
using(MemoryStream ms = new MemoryStream())
{
     //code
     //return ms; I commented it out because it makes no sense at all
}



严格等同于


is strictly equivalent to:

MemoryStream ms = new MemoryStream();
try
{
     //code
}
finally
{
    ms.Dispose();
}



换句话说,这是一种自动调用 IDisposable.Dispose()的方法。解决方案1作者的注释:一般情况下,处理与垃圾收集和回收内存无关。事实上, IDisposable 经常用于回收非托管内存,但还有很多其他用途。



请参阅:

http://msdn.microsoft.com/en-us/library/ yh598w02.aspx [ ^ ],

了解C#中的'using'语句 [ ^ ],

http ://msdn.microsoft.com/en-us/library/system.idisposable%28v=vs.110%29.aspx [ ^ ]。



-SA


In other words, this is an automatic way of calling IDisposable.Dispose(). A note for the author of Solution 1: In general case, disposal have nothing to do with garbage collection and reclaiming memory. In fact, IDisposable often used in reclaiming unmanaged memory, but there are many other uses.

Please see:
http://msdn.microsoft.com/en-us/library/yh598w02.aspx[^],
Understanding the 'using' statement in C#[^],
http://msdn.microsoft.com/en-us/library/system.idisposable%28v=vs.110%29.aspx[^].

—SA


这篇关于我从Using语句返回的对象会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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