我正在写的生物节律的应用程序。 为了测试它,我有一个按钮和一个图片框的形式。 当我点击按钮i做

myPictureBox.Image = GetBiorhythm2();

哪些运行确定用于第一次,的但在第二次点击它会导致以下情况例外:

System.ArgumentException: Parameter is not valid.
   at System.Drawing.Graphics.CheckErrorStatus
   at System.Drawing.Graphics.FillEllipse
   at Larifari.Biorhythm.Biorhythm.GetBiorhythm2 in c:\delo\Horoskop\Biorhythm.cs:line 157
   at Larifari.test.Button1Click in c:\delo\Horoskop\test.Designer.cs:line 169
   at System.Windows.Forms.Control.OnClick
   at System.Windows.Forms.Button.OnClick
   at System.Windows.Forms.Button.OnMouseUp
   at System.Windows.Forms.Control.WmMouseUp
   at System.Windows.Forms.Control.WndProc
   at System.Windows.Forms.ButtonBase.WndProc
   at System.Windows.Forms.Button.WndProc
   at ControlNativeWindow.OnMessage
   at ControlNativeWindow.WndProc
   at System.Windows.Forms.NativeWindow.DebuggableCallback
   at ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop
   at ThreadContext.RunMessageLoopInner
   at ThreadContext.RunMessageLoop
   at System.Windows.Forms.Application.Run
   at Larifari.test.Main in c:\delo\Horoskop\test.cs:line 20

这会导致错误的切下来的功能是:

public static Image GetBiorhythm2() {
        Bitmap bmp = new Bitmap(600, 300);
        Image img = bmp;
        Graphics g = Graphics.FromImage(img);

        Brush brush = Brushes.Black;
        g.FillEllipse(brush, 3, 3, 2, 2); //Here the exception is thrown on the second call to the function

        brush.Dispose(); //If i comment this out, it works ok.

        return img;
 }

如果我注释掉刷处置它工作正常,但我不是满意了,希望找到一个替代的解决方案。你能帮助我吗?

有帮助吗?

解决方案

它看起来像你想配置一个静态的,这会导致一些问题,下一次它的使用的:

    Brush brush = Brushes.Black;
    g.FillEllipse(brush, 3, 3, 2, 2); //Here the exception is thrown on the second call to the function

    brush.Dispose(); //If i comment this out, it works ok.

当设置刷= Brushes.Black,实际上是设定刷作为参考(或指针),以静态Brushes.Black。通过设置它,你写有效的:

    Brushes.Black.dispose();

当你绕回来再次使用黑色画笔,运行时说,你不能因为它已经被处理掉,而不是g.FillEllipse有效的参数()

有一个更好的方式来写,这可能是只是简单的:

    g.FillEllipse(Brushes.Black, 3, 3, 2, 2);

或者,如果你想成为非常复杂的吧:

    Brush brush = Brushes.Black.Clone();
    g.FillEllipse( brush, 3, 3, 2, 2 );
    brush.Dispose();

或者,如果你不关心的东西找错,只是注释掉brush.Dispose();线在原始代码。

其他提示

Bruhes.Black是系统资源,而不是为你处理。运行时管理的Brushes类,笔,以及其他此类对象的刷子。它创建并配置这些对象的要求,保持经常使用的项活着,使其不必不断创建和销毁它们。

对于画笔类文档说:

  

在刷类包含静态   只读返回一个属性   由表示的颜色的画刷对象   属性名称。你通常做   没有明确处置的   通过刷属性在这个返回   类,除非它被用来构造   一个新的刷。

在短,不调用Dispose系统提供对象。

我不认为你需要调用.Dispose上静电刷,只要你创建新的。虽然,个人,我会用利用语法..即:

using (Brush brush = new SolidBrush(...))
{
    g.FillEllipse(brush, 3, 3, 2, 2);
}

和你应该做同样的事情与图形对象的创建。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top