簡體   English   中英

並且非靜態字段、方法或屬性需要 Object 引用

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

我試圖通過 class 在表格上繪制東西。 這是代碼。

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();
    }

問題是g = frmMainGame.picGeneral.CreateGrpahics; . 由於控件不是 static 我將如何 go 關於通過 class 訪問它而不是移動代碼並且必須將其重新編碼為表單本身的代碼。

幾個選項 spring 要記住:

  1. 將問題傳遞給調用者,即讓他們將實際引用作為參數傳遞。 如果他們不知道,請讓他們的調用者將其傳遞等等。畢竟,必須有人知道您需要使用哪個 object。
  2. 如果您知道只有一個感興趣的引用,那么您可以在創建 object 時將其靜態存儲在某處。 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.

您可以添加一個事件來處理您的 PictureBox.Paint 方法

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

把你的方法變成擴展方法

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM