Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/99.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 关闭表单后如何保存变量的值_C#_Windows Forms Designer - Fatal编程技术网

C# 关闭表单后如何保存变量的值

C# 关闭表单后如何保存变量的值,c#,windows-forms-designer,C#,Windows Forms Designer,在Windows窗体中,我有一个独立的类Indicators.cs和一个窗体Food。在这个类中,我有一个变量,我正在改变它的形式 当我打开表单、更改变量、关闭表单并再次打开它(不关闭程序)时,变量的值是旧的。为什么会这样 表格: namespace WF { public partial class Computer : Form { Indicators indicators = new Indicators(); public Comput

在Windows窗体中,我有一个独立的类Indicators.cs和一个窗体Food。在这个类中,我有一个变量,我正在改变它的形式

当我打开表单、更改变量、关闭表单并再次打开它(不关闭程序)时,变量的值是旧的。为什么会这样

表格:

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

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

namespace WF
{
    class Indicators
    {
        public Indicators()
        {

            this.isComputerAlreadyRunning = false;            
        }

        public bool isComputerAlreadyRunning;
    }
}

在form类中创建一个显示表单并返回结果的方法。这类似于MessageBox.Show方法。在下面的示例中,FoodForm有一个名为ShowForm的方法。此方法返回一个名为FoodFormResult的自定义类,该类在表单关闭后具有表单所需的所有结果

public FoodFormResult ShowForm()
    {
        return new FoodFormResult(
            ShowDialog() == DialogResult.OK, 
            _indicators);
    }

每次创建表单类(例如new FoodForm())时,表单中的所有现有值都将丢失。

有多种方法可实现此目的。您可以创建委托、保存到表单资源、保存到外部文件、保存到设置/Appconfig文件等等

另一个但出于安全原因不太推荐的选项是:您可以在应用程序的main方法中创建一个内部或公共静态变量..然后在需要设置此变量时

当您需要调用该变量时:

//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!");
}

在哪里实例化Indicators.cs对象?如果它在表单中,那么它的作用域只在那里,当表单关闭时它将消失。@是的,它在表单中,但我需要它来访问变量,然后需要在表单外部实例化Indicators类。可以将对象的引用传递给窗体,以便访问变量。那么它将超越你的形式范围而存在。