简体   繁体   中英

And Object reference is required for the non-static field, method, or property

I'm attempting to draw things on a form through a class. Here is the code.

public static void DrawStatBars()
    {
        Graphics g = Graphics.FromImage(Graphic.StatBarBackbuffer);
        Font fnt = new Font("Microsoft Sans Serif", 8, FontStyle.Bold);
        g.DrawImage(Graphic.EmptyHPBar, new Point(12, 12));
        g.DrawImage(Graphic.EmptyManaBar, new Point(12, 35));
        g.DrawImage(Graphic.EmptyEXPBar, new Point(12, 58));
        g.DrawImage(Graphic.HPBar, new Rectangle(12, 15, (int)picHpWidth, Graphic.HPBar.Height), new Rectangle(0, 0, (int)picHpWidth, Graphic.HPBar.Height), GraphicsUnit.Pixel);
        g.DrawImage(Graphic.ManaBar, new Rectangle(12, 38, (int)picManaWidth, Graphic.ManaBar.Height), new Rectangle(0, 0, (int)picManaWidth, Graphic.ManaBar.Height), GraphicsUnit.Pixel);
        g.DrawImage(Graphic.EXPBar, new Rectangle(12, 61, (int)picEXPWidth, Graphic.EXPBar.Height), new Rectangle(0, 0, (int)picEXPWidth, Graphic.EXPBar.Height), GraphicsUnit.Pixel);
        g.DrawString(lblHPText, fnt, new SolidBrush(Color.Black), 40, 15);
        g.DrawString(lblManaText, fnt, new SolidBrush(Color.Black), 40, 38);
        g.DrawString(lblEXPText, fnt, new SolidBrush(Color.Black), 40, 63);
        g.Dispose();


        g = frmMainGame.picGeneral.CreateGraphics;
        g.DrawImage(Graphic.StatBarBackbuffer, new Point(0, 0));
        g.Dispose();
    }

The problem is g = frmMainGame.picGeneral.CreateGrpahics; . Since the control is not static how would I go about accessing it through a class instead of moving the code and having to re-code it to be in the code for the form itself.

A couple of options spring to mind:

  1. Pass the problem to the caller, ie get them to pass the actual reference in as a parameter. If they don't know, then get their caller to pass it in etc. After all, someone must know which object you need to use.
  2. If you know there's only going to be one reference of interest, then you can store that statically somewhere when the object gets created. Depending on the structure of your application you may want to store it in the object's own class, in the creator's class, in the user's class, or in an application class.

You could add an event to handle your PictureBox.Paint method

private void picGeneral_Paint(object sender, PaintEventArgs e)
{
    // Use e.Graphics to do your drawing!
    e.Graphics.DrawStatsBars();
}

Turn your method into an extension method

public static class GraphicsExtensions
{
    public static void DrawStatsBars(this Graphics g)
    {
        // Your code
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM