我在處置和最終確定之間進入神經。這裏是我的示例代碼:C#處置:處置時和處置它
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);
}
結果是:
Before dispose. Name is My Car
This object has been disposed
After dispose. Name is My Car
我的問題是:因爲C#會自動using{}
後處理的對象,所以我覺得在行「處置後」。 anotherCar.name
必須爲NULL。爲什麼它仍然是「我的車」?
而我的另一個問題是:我的書說,你不應該使用GC.Collect()
出於某種原因,其中之一是性能。那麼,誰處置對象?如果是垃圾收集器,也讓我覺得dipose()
有finalizer()
謝謝:)