【问题标题】:Making a global variable int制作一个全局变量 int
【发布时间】:2018-11-15 11:10:25
【问题描述】:

当我们登录时,我想在不同的窗口中使用EmployeeId。有什么好的解决方案?

所以在登录后,EmployeeId所有窗口public int

我们使用 SQL Server 进行登录。

【问题讨论】:

标签: c# sql-server int


【解决方案1】:

假设应用程序是 WinForms 或 WPF 则:

class Program
{
    public static int EmployeeId {get;set;}

}

class OtherWindow
{
    void Function()
    {
       int employeeId = Program.EmployeeId;

    }
}

如果您的应用是 Web 服务器或其他“多用户”系统,那么您将需要找到不同的方式。

【讨论】:

    【解决方案2】:

    为什么不呢?如果您想将EmployeeId 视为一个全局变量,您可以实现如下例程。但请确保EmployeeId线程安全的

    namespace MyNameSpace {
      ...
      public static class MyEnvironmentVariables {
        // Lazy<int> - let EmployerId be thread safe (and lazy)
        private static Lazy<int> GetEmployeeId = new Lazy<int>(() => {
          //TODO: implement it
          return ObtainEmployeeIdFromDataBase();
        });
    
        public static int EmployeeId {
          get {
            return GetEmployeeId.Value;
          }
        }
      }
    

    然后在using static 的帮助下,您可以看到它就像您有一个全局变量

      // static: we don't want to mention pesky MyEnvironmentVariables
      using static MyNameSpace.MyEnvironmentVariables;
    
      ...
      public class MyDifferentWindow {
        ...
        public void MyMethod() {
          // we can use EmployerId as if it's a global variable
          int id = EmployeeId;
          ... 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-24
      • 2011-10-26
      • 1970-01-01
      • 2013-12-30
      • 1970-01-01
      相关资源
      最近更新 更多