手动销毁C#对象 [英] Manually destroy C# objects

查看:1054
本文介绍了手动销毁C#对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当新的学习C#(从Java和C ++背景),我有一个关于手动垃圾处理的问题:是它甚至可以手动消灭在C#中的对象?我知道关于的IDisposable 接口,但假设我处理,我没有写一个类,它没有实现呢?它不会有一个 .Dispose()方法,让和使用{} 不在,而 .Finalize 始终为保护私人所以这不是一个选项无论是。

I am fairly new to learning C# (from Java & C++ background) and I have a question about manual garbage disposal: is it even possible to manually destroy an object in C#? I know about the IDisposable interface, but suppose I'm dealing with a class which I didn't write and it doesn't implement it? It wouldn't have a .Dispose() method, so that and using { } is out, and .Finalize is always either protected or private so that's not an option either.

(我只是想了解什么是的可能的在C#在这种情况下,我想,如果一切都失败了我所能的继承假想 ImNotDisposable 类,以便它的确实的实现IDisposable。)

(I am just trying to learn what is possible in C# in this case. I suppose if all else fails I could inherit the hypothetical ImNotDisposable class so that it does implement IDisposable.)

推荐答案

您不要手动销毁.NET对象。这就是作为一个托管的环境是怎么一回事。

You don't manually destroy .Net objects. That's what being a managed environment is all about.

你可以做的就是调用 GC.Collect的()来迫使一般的集合。然而,这几乎从来没有一个好主意,你不能让你的目标特定对象。事实上,如果你仍然有这个对象,你可以使用一个参考来告诉它反对针对我可以向你保证它的不会的收集。

What you can do is call GC.Collect() to force a general collection. However, this almost never a good idea and you can't make it target your specific object. In fact, if you still have a reference to this object that you could use to tell it which object to target I can promise you that it won't be collected.

相反,它可能会更好简单的 pretend 的是不使用非托管资源,而不是通过访问你的程序中任何其他对象的任何对象立即销毁。我知道这种情况不会发生,但在这一点的对象仅仅是一个像任何其它存储器块。你不能收回它,它最终会被收集起来,所以它可能只是都没有见到你。

Instead, it's probably better to simply pretend that any object that doesn't use unmanaged resources and is not reachable by any other object in your program is immediately destroyed. I know this doesn't happen, but at this point the object is just a block of memory like any other. You can't reclaim it and it will eventually be collected, so it may just as well be dead to you.

有关IDisposable的最后一个音符。您应该只使用它的类型包装的非托管的资源:之类的东西插座,数据库连接,GDI对象等

One final note about IDisposable. You should only use it for types that wrap unmanaged resources: things like sockets, database connections, gdi objects, etc.

这篇关于手动销毁C#对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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