2014-05-04 27 views
1

在WindowsForms中我有一個獨立的類Indicators.cs和表格食品。在課堂上,我有一個變量,我正在改變形式。如何在關閉表格後保存變量的值

當我打開窗體時,更改變量,關閉窗體並再次打開它(不關閉程序),那麼變量的值是舊的。爲什麼這樣?

形式:

namespace WF 
{ 
    public partial class Computer : Form 
    { 
     Indicators indicators = new Indicators(); 

     public Computer() 
     { 
      if (indicators.isComputerAlreadyRunning == false) 
       indicators.isComputerAlreadyRunning = true; 
     } 
    } 
} 

Indicators.cs

namespace WF 
{ 
    class Indicators 
    { 
     public Indicators() 
     { 

      this.isComputerAlreadyRunning = false;    
     } 

     public bool isComputerAlreadyRunning; 
    } 
} 
+2

你在哪裏實例化你的Indicators.cs對象?如果它在你的表單內,那麼它的範圍只在那裏,當表單關閉時它將消失。 –

+0

@intracept是的,它在表單內,但我需要它來訪問變量 – dima

+1

您需要在表單外部實例化Indicators類。您可以將對象的引用傳遞給您的表單,以便您可以訪問該變量。那麼它會超出你的形式的範圍。 –

回答

1

創建形式類的方法,其示出的形式,並且返回一個結果。這與MessageBox.Show方法類似。在下面的例子中,FoodForm有一個名爲ShowForm的方法。此方法返回一個名爲FoodFormResult的自定義類,它在關閉後具有表單所需的所有結果。每當創建表單類(例如,新的FoodForm())時,表單中的所有現有值都會丟失。

1

很多方法可以做到this..You可以創建一個委託,保存到形式的資源,保存到外部文件,保存到設置/ AppConfig的file..So上..

而另一個卻並不多推薦安全原因選擇是:您可以創建在application..Then的主要方法內部或公共靜態變量,當你需要設置這個變量..

而當你需要調用該變量:

//Your main method example 
static class Program 
{ 
    internal static bool AreYouOKAY = false; 
    // or public static bool as your needs 

    static void Main() 
    { 
     ........ 
    } 

/// And in your form 

Program.AreYouOKAY = true; 

// After your form closed.. from another form just call as above 

if(Program.AreYouOKAY) 
{ 
    MessageBox.Show (" Yeah! I'm Ok!"); 
}