【发布时间】:2013-12-10 10:11:42
【问题描述】:
我必须使用 Windows 窗体用 C# 编写游戏。对于我在屏幕上的绘图方法,我得到了一个奇怪的 System.ObjectDisposedException,它在我的一个图形对象被实例化时产生。这是有问题的代码:
// Graphics variables.
Graphics graphics;
Graphics backBufferObject;
Bitmap backBuffer;
// Graphics and backBuffer are instantiated, elsewhere, in the constructor.
private void DrawScreen()
{
// Copy the BackBuffer to Graphics Object.
using (graphics = Graphics.FromImage(backBuffer))
using (backBufferObject = this.CreateGraphics())
{
// Draw BackBuffer to screen (buffer switching).
backBufferObject.DrawImage(backBuffer, 0, 0, this.Width, this.Height);
graphics.DrawImage(Properties.Resources.scary_pacman, new Rectangle(
this.Width / 2 , this.Height / 2, 32, 32));
graphics.Clear(Color.Thistle); // Clear BackBuffer for efficient rendering.
}
}
引发 System.ObjectDisposedException 的有问题的行是:using (backbufferObject = this.CreateGraphics())。我不确定为什么在这个特定的点抛出这个异常,因为这个对象正在被重新实例化,而它被放置在使用括号的末尾。到目前为止,我已经尝试将这两行放在using 语句中,因为它们受到 IDisposable 的影响。
可能值得注意的是,在我在运行时关闭 Windows 窗体后引发了错误。那么为什么这个 Graphics 对象会在这个特定的实例中被丢弃呢?
【问题讨论】: