【问题标题】:How to make global variables? [closed]如何制作全局变量? [关闭]
【发布时间】:2013-12-30 16:24:58
【问题描述】:

在使用C# .NET 的Windows 应用程序开发中,如何创建一个全局变量或类的全局实例,然后可以直接被所有其他Windows 窗体使用,例如form1、form2等

【问题讨论】:

  • 问题是:你想要使用全局变量吗?如果是这样,您尝试过什么?

标签: c# .net winforms visual-studio-2010 c#-4.0


【解决方案1】:

您可以创建一个static 类并在其中定义一个静态变量。

您项目中的所有类都可以使用MyGlobalVariables.GlobalVariable引用它

public static class MyGlobalVariables
{
   public static int GlobalVariable;
}

【讨论】:

    【解决方案2】:

    创建一个包含全局变量的public static class

    例如。

    public static class GlobalValues
    {
          public static int UserId{get;set;}
    }
    

    阅读更多关于C# Global Variable

    另外我猜你应该阅读Classes and Structs

    【讨论】:

      【解决方案3】:

      创建单例类,以便可以创建一次实例并跨应用程序使用

      public class Global 
      {
          private static readonly Global instance = new Global();
          public static Global Instance
          {
              get
              {
                  return instance;
              }
          }
      
          Global()
          {
          }
          public string myproperty
          {
              get;set;
          }
          }
      

      用法: Global.Instance.myproperty

      【讨论】:

        【解决方案4】:

        将其设为静态变量和静态类,例如

        private static string foo = "this is static";

        public static class Bar {}

        【讨论】:

          猜你喜欢
          • 2016-03-01
          • 1970-01-01
          • 2012-09-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-29
          相关资源
          最近更新 更多