程序成功没有错误,但此方法不起作用

时间:2014-12-14 15:57:28

标签: c#

class game_rule
{
    public void DoAttack()
    {
        Form1 prgBar = new Form1();
        prgBar.progressBar1.Increment(-200);
        SystemSounds.Asterisk.Play();
    }
}

但是下面的代码(来自form1-direct)工作。

public partial class Form1 : Form
{
  game_rule dt = new game_rule();
  private void button2_Click(object sender, EventArgs e)
  {
    progressBar1.Increment(-200); // this is work
    dt.DoAttack(); // this is not work... but there is no build error at all!
  }
}

编辑问题: form form1 "progressBar1.Increment(-200);"正在使用来自类game_rule的prgBar.progressBar1.Increment(-200);,而不是“dt.DoAttack();”

1 个答案:

答案 0 :(得分:0)

prgBar.Show()

这是你需要的吗?你忘了展示新表格吗?

编辑:

我正在回复你的评论...

您需要一个静态属性才能从其他地方访问该表单:

public partial class Form1 : Form
{
  // This is you constructor (not shown in your sample code).
  public Form1()
  {
    InitializeComponent();
    Instance = this;
  }

  public static Form1 Instance { get; private set;}

  game_rule dt = new game_rule();
  private void button2_Click(object sender, EventArgs e)
  {
    progressBar1.Increment(-200); // this is work
    dt.DoAttack(); // this is not work... but there is no build error at all!
  }
}


class game_rule
{
    public void DoAttack()
    {
        Form1.Instance.progressBar1.Increment(-200);
        SystemSounds.Asterisk.Play();
    }
}

或其他方法可能是依赖注入(不是一个完美的方法,但它是一个良好的开端):

public partial class Form1 : Form
{

  game_rule dt = new game_rule();
  private void button2_Click(object sender, EventArgs e)
  {
    progressBar1.Increment(-200); // this is work
    dt.DoAttack(this); // this is not work... but there is no build error at all!
  }
}


class game_rule
{        
    public void DoAttack(Form1 form)
    {
        form1.progressBar1.Increment(-200);
        SystemSounds.Asterisk.Play();
    }
}