C#Dispose:何时处置以及由谁处置 [英] C# Dispose : when dispose and who dispose it
问题描述
在处理和完成之间,我很紧张。这是我的示例代码:
公共类Car:IDisposable
{
公共字符串名称;
public Car()
{
name = My Car;
}
public void Dispose()
{
Console.WriteLine(此对象已被处置);
}
}
public static void Main()
{
Car anotherCar;
使用(var car = new Car())
{
anotherCar = car;
Console.WriteLine(处置之前。名称为: + anotherCar.name);
}
Console.WriteLine(处置后。名称为: + anotherCar.name);
}
结果是:
处置之前。名称是My Car
此对象已被处置
处置后。名称是我的车
我的问题是:因为C#会在之后自动处理对象使用{}
,所以我认为在处理后行。 anotherCar.name
必须为NULL。为什么它仍然是我的车?
我的另一个问题是:我的书说你不应该使用 GC.Collect()
出于某种原因,其中之一就是性能。那么,谁处置对象?如果那是垃圾收集器,那么我也认为 dipose()
与 finalizer()
具有相同的性能问题。 p>
谢谢:)
我认为您误解了Dispose的实际作用。它不会破坏您的对象,将任何内容设置为null或执行任何形式的魔术。当使用using语句时,仅保证将调用Dispose。您在Dispose方法中执行的操作决定了对象的行为。不是语言或.NET框架。
I'm getting in nerve between dispose and finalize. Here is my example code:
public class Car:IDisposable
{
public string name;
public Car()
{
name = "My Car";
}
public void Dispose()
{
Console.WriteLine("This object has been disposed");
}
}
public static void Main()
{
Car anotherCar;
using (var car = new Car())
{
anotherCar = car;
Console.WriteLine("Before dispose. Name is: "+anotherCar.name);
}
Console.WriteLine("After dispose. Name is: "+anotherCar.name);
}
The result is:
Before dispose. Name is My Car
This object has been disposed
After dispose. Name is My Car
My question is : because C# will automatically dispose object after using{}
, so I think at line "After dispose". anotherCar.name
must be NULL. why it still be "My Car" ?
And my another question is : my book said that you shouldn't use GC.Collect()
for some reason and one of these is Performance. So, who dispose object ? If that is Garbage Collector,too so I think dipose()
has the same performance issues with finalizer()
Thanks :)
I think you are misunderstanding what Dispose actually does. It doesn't destroy your object, set anything to null, or otherwise perform any sort of magic. When you use the using statement, that just guarantees that Dispose will be called. What you do in your Dispose method is what determines the behavior of your object. Not the language or .NET framework.
这篇关于C#Dispose:何时处置以及由谁处置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!