System.Drawing对象非托管资源处理

问题描述:

我有下面的代码:

using System.Drawing;
...
Graphics _graphics = Graphics.FromImage(...)
...
public void Draw(Stream stream, Rectangle rect, Color color) {
    _graphics.FillRectangle(new SolidBrush(Color), 0, 0, Width, Height);
    _graphics.DrawImage(new Bitmap(stream), rect);
}

我应该使用 new Bitmap (...)
新的SolidBrush(...)上的相同问题

是的,您应该使用语句包装它们。此外,您应该确保在您在此类中使用的 _graphics 实例上调用Dispose方法。这可以通过让包含类实现 IDisposable 来实现,以便这个类的使用者可以使用c>将它包装在语句。

Yes, you should wrap them in using statements. Also you should ensure that the Dispose methods is invoked on the _graphics instance that you are using in this class. This could be done by having the containing class implement IDisposable so that the consumer of this class could wrap it in a using statement.