2014-04-06 96 views
0

海蘭,我如何獲得一個變量參數從一個方法到另一個

我有以下constuctor:

public partial class SelectSize : Form 
    { 
     public SelectSize(String name) 
     { 
      this.Name = name; 
      InitializeComponent(); 
     } 

     public String Name 
     { get; set; } 

,我想名字在我下面的方法使用它:

p private void button1_Click(object sender, EventArgs e) 
    { 

     if (((int.Parse(noRows.Text) % 2) == 0) && (((int.Parse(noCols.Text) % 2) == 0)) && ((int.Parse(noRows.Text) == 
      int.Parse(noCols.Text))) && ((int.Parse(noRows.Text) > 6) && ((int.Parse(noRows.Text) > 6)))) 
     { 
      //String name = this.Name; 
      PlayMe f = new PlayMe(int.Parse(noCols.Text), int.Parse(noCols.Text), Name); 
      this.Hide(); 
      f.ShowDialog(); 
      this.Close(); 

但我得到名爲空引用。

我如何將一個變量轉移到另一個方法?

誠懇,

+1

都在同一類這些方法? –

+0

是的,他們是。構造函數中的名稱來自另一個表單。構造函數正確地接收它的參數。 – MxM

回答

0

我現在沒有爲什麼我的上述代碼不工作的原因。

謝謝大家的幫助,您的好建議讓我改進了我的代碼並找到了解決方案。

最初的形式看起來像波紋管:

private void nXNGameToolStripMenuItem_Click(object sender, EventArgs e) 
     { 

      SelectSize ss = new SelectSize(this); 
      ss.ShowDialog(); 

     } 

現在SelectSize形式和button_Click是:

public partial class SelectSize : Form 
    { 
     MainWin f1; 
     public SelectSize(MainWin f1) 
     { 
      this.f1 = f1; 
      InitializeComponent(); 
     } 

     public String Name 
     { get; set; } 

     private void button1_Click(object sender, EventArgs e) 
     { 

      if (((int.Parse(noRows.Text) % 2) == 0) && (((int.Parse(noCols.Text) % 2) == 0)) && ((int.Parse(noRows.Text) == 
       int.Parse(noCols.Text))) && ((int.Parse(noRows.Text) > 6) && ((int.Parse(noRows.Text) > 6)))) 
      { 
       //String name = this.Name; 
       PlayMe f = new PlayMe(int.Parse(noCols.Text), int.Parse(noCols.Text), f1.Name); 
       this.Hide(); 
       f.ShowDialog(); 
       this.Close(); 
0

如果this.Name爲null,則不同的構造函數被調用或空實際上傳遞給構造函數。檢查一下。 當然,它可能在此期間被覆蓋。例如。從我們的角度來看。因爲我們不知道所有的代碼,this.Name = null;可能在InstanciateComponent()

那麼,可能會發生這兩種方法不在這個類的相同(相同)的實例上執行。如果他們真的相同,比較ojbjects的地址。

順便說一句,你應該撥打電話this.Name而不是this.nameInstanciateComponent()應該是instanciateComponent()

0

除非設置它,否則名稱將爲空。你需要給一個默認值來獲得它。

+0

在構造函數中接收到的名稱不爲null,但在button1_Click()爲null時:-( – MxM

0

當然這將是空引用,因爲你不初始化它,你將如何設置名稱的值

+0

該名稱在SelectSize(String name)構造函數中具有值。 – MxM

0

_button1_Click_? 我猜你有Form1.Name

當你寫

this.Name = "value"; 

碰撞你試圖改變你的Form1的名稱

UPD:

試試這個:

namespace test 
{ 
    public partial class SelectSize : Form 
    { 
     public SelectSize(String name) 
     { 

      InitializeComponent(); 
      this.Name = name; 
     } 

     public String Name 
     { get; set; } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      MessageBox.Show(this.Name); // It must show a string from SelectSize's constructor 
     } 

    } 
} 
+0

是的。我更改Form1的名稱,並在PlayMe表單簽名中使用此名稱作爲參數PlayMe f = new PlayMe(int.Parse(noCols.Text),int.Parse(noCols.Text),Name); – MxM

+0

@MariusMoraru,看我的更新 – Roman

相關問題