Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.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
.Net引用表单应用程序变量_.net_Reference_Scope - Fatal编程技术网

.Net引用表单应用程序变量

.Net引用表单应用程序变量,.net,reference,scope,.net,Reference,Scope,我的应用程序主窗体中有一个公共变量“testStr”。我有一个tabControl,它添加了加载了用户控件的选项卡。如何从这些用户控件引用“testStr”?我可以想象它是Application.*还是parentForm.*。。。但是我尝试的每件事都不起作用,不知道怎么做,而且我对.net有点陌生。。。在flex builder中,我将执行类似于parentApplication.testStr的操作 任何帮助都将不胜感激。。。我确信这是非常基本和简单的操作。如果选项卡控件直接位于顶级表单中,

我的应用程序主窗体中有一个公共变量“testStr”。我有一个tabControl,它添加了加载了用户控件的选项卡。如何从这些用户控件引用“testStr”?我可以想象它是Application.*还是parentForm.*。。。但是我尝试的每件事都不起作用,不知道怎么做,而且我对.net有点陌生。。。在flex builder中,我将执行类似于parentApplication.testStr的操作


任何帮助都将不胜感激。。。我确信这是非常基本和简单的操作。

如果选项卡控件直接位于顶级表单中,那么

((this.Parent) as MyForm).testStr
否则,您可能需要继续执行。
Parent
,直到到达堆栈顶部,然后转换为表单类型

或者

((this.FindForm()) as MyForm).testStr

我以前不知道…

您可以将对表单实例的引用保存在某个静态变量中。例如,您可以编辑
程序.cs

class Program {
     public static MyForm MainForm { get; private set; }
     static void Main() {
         // ...
         Application.Run(MainForm = new MyForm());
         // ...
     }
}

然后,您可以使用
Program.MainForm.testStr
引用
testStr
,您可以向上迭代以获得值:

class MyControl : UserControl
{
   public string GetMyStr()
   {
      for (Control c = this.Parent; c != null; c = c.Parent)
      {
         if (c is MyForm)
         {
            return c.testStr; // I recommend using a property instead
         }
      }
      return null;
   }
}
或者,如果该值在所有实例中都相同,则将其声明为常量、静态只读字段或普通静态字段:

  class MyForm
   {
      public static const string TESTSTR = "...";
   }

   class MyControl : UserControl
   {
      public void DoSomething()
      {
         string s = MyForm.TESTSTR;
      }
   }

在它自己的类中存储像testStr(以及任何其他相关的)这样的信息,并共享对其他需要使用它的类的引用,怎么样

因此,MainForm将创建这个新类的一个实例,并在创建每个UserControl时传递对它们的引用。这样,UserControls就不需要知道MainForm的任何信息,只需要知道它们处理的数据。如果你改变应用程序的布局,它也会让事情变得更容易。总是假设父级高于一级或顶层父级是您想要的表单,这对更改不是很友好