如何创建一个全局“C#”类

时间:2013-12-21 14:19:44

标签: c# sql database

如何为数据库连接创建全局“C#”类,以便: 1.所有课程和控制都可以处理 2.重新召开所有会议,直至申请结束 3.关闭Windows窗体应用程序时断开与服务器的连接

2 个答案:

答案 0 :(得分:1)

使用 Singleton 设计模式。 Singleton确保有一个类的全局访问点,并且该类只有一个实例。它远远优于静态类。 Singleton vs. Static Class.

的Singleton

public class Singleton
{
    private static Singleton instance;

    // Private Constructor.
    private Singleton()
    {
        // This ensures no other class but this can create instances of the Singleton.
    }

    // Returns the instance of this class.
    public static Singleton getInstance()
    {
        // Check if an instance of this class already exists.
        if(instance == null)
           // It doesn't exist so create it. 
           instance = new Singleton();

        // Return the instance.
        return instance;
    }
}

答案 1 :(得分:1)

您可以尝试使用 Singleton设计模式

http://en.wikipedia.org/wiki/Singleton_pattern

典型的线程安全实现可以是这样的:

public sealed class Program {
  private static Object s_SyncObj = new Object();

  private static volatile Program s_Instance;

  private Program() {
    ...    
  }

  public static Program Instance {
    get {
      if (!Object.ReferenceEquals(null, s_Instance)) 
        return s_Instance;

      lock (s_SyncObj) {
        if (!Object.ReferenceEquals(null, s_Instance)) 
          return s_Instance;

        s_Instance = new Program(); 
      }

      return s_Instance; 
    }
  }
}

您还可以尝试仅使用静态类

public static class Program {
  ...
}