由FileInfo,DirectoryInfo持有的发布对象 [英] Release Objects held by FileInfo, DirectoryInfo

查看:590
本文介绍了由FileInfo,DirectoryInfo持有的发布对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何释放下面这些功能所保存的对象?

How do i release respectively dispose the objects which are held from these fuctions below?

 Dim drvInfo As DirectoryInfo = New DirectoryInfo("C:\myFolder")
 Dim filesInfo() As FileInfo = drvInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly)


Try
      For Each file As FileInfo In filesInfo
       If Not file.Attributes = FileAttributes.System Then
       My.Computer.FileSystem.RenameFile(file.FullName, "myFile" + file.Extension)
      Next
Catch
End Try

推荐答案

您只需要处置实现System.IDisposable的类型的对象.请参阅:
http://msdn.microsoft.com/en-us/library/system.idisposable.aspx [^ ].

如果使用临时对象,最好的方法是使用using语句,即使抛出异常,该语句也有助于处理创建的对象.实际上,它的工作原理与try-finally块完全相同:
http://msdn.microsoft.com/en-us/library/htd05whh.aspx [ ^ ].

如果您使用的对象超出单个方法的范围,则需要使用链策略:将所有对象都放在父对象的dispose方法中. …好吧,看来我要离开原来的话题了……:-)



您不应将处置与托管内存分配混为一谈.您不需要做任何事情来释放它,垃圾收集器可以做到:
http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29 [ ^ ].

实际上,这就是为什么.NET(CLR)代码被称为托管"的原因.
接口System.IDisposable可以用于与释放某些东西无关的任何目的.而是,它用作一种机制,以确保始终执行某些关闭"操作.这种机制最典型的应用之一就是释放非托管资源,例如GDI对象.这是一个使用与释放任何内容无关的处置的有趣示例:
>沙漏鼠标光标始终会变回其原始图像. [
You only need to dispose object of the types implementing System.IDisposable. Please see:
http://msdn.microsoft.com/en-us/library/system.idisposable.aspx[^].

If you work with temporary object, the best way of doing it is using the using statement, which helps to dispose the object you create even if an exception is thrown. Actually, it works exactly like with try-finally block:
http://msdn.microsoft.com/en-us/library/htd05whh.aspx[^].

If you use your objects beyond the scope of a single method, you need to use the chain strategy: dispose everything in the parent''s dispose method. …OK, it looks like I''m going to far from the original topic… :-)



You should not mix up disposal with managed memory allocation. You never need to do anything to release it, the garbage collector does it:
http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29[^].

Actually, this is why .NET (CLR) code is called "managed".

The interface System.IDisposable can be used for any purposes which do not have to be related to release of something. Rather, it is used as a mechanism to guarantee that some "closing" action is always performed. One of the most typical application of this mechanism is the release of unmanaged resources, as in the case of GDI object. This is an interesting example of using disposing not related to releasing of anything:
Hourglass Mouse Cursor Always Changes Back to its Original Image. How?[^] (please also see the alternative solution, which is more generalized).

—SA


这篇关于由FileInfo,DirectoryInfo持有的发布对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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