调用已释放对象的方法是否合法?如果是,为什么?
在下面的演示程序中,我有一个可处理的类 A
(它实现了 IDisposable
接口)。据我所知,如果我将可处理对象传递给 using()
构造,则 Dispose()
方法会在关闭括号时自动调用:
A a = new A();
using (a)
{
//...
}//<--------- a.Dispose() gets called here!
//here the object is supposed to be disposed,
//and shouldn't be used, as far as I understand.
如果这是正确的,那么请解释一下这个程序的输出:
public class A : IDisposable
{
int i = 100;
public void Dispose()
{
Console.WriteLine("Dispose() called");
}
public void f()
{
Console.WriteLine("{0}", i); i *= 2;
}
}
public class Test
{
public static void Main()
{
A a = new A();
Console.WriteLine("Before using()");
a.f();
using ( a)
{
Console.WriteLine("Inside using()");
a.f();
}
Console.WriteLine("After using()");
a.f();
}
}
输出 (ideone):
Before using()
100
Inside using()
200
Dispose() called
After using()
400
如何在已释放的对象 a
上调用 f()
?这样做是否允许?如果是,为什么?如果不是,那么为什么上面的程序在运行时没有抛出异常?
我知道使用 using
的流行结构是这样的:
using (A a = new A())
{
//working with a
}
但我只是在试验,这就是为什么我写得不同的原因。