如题。
本人菜鸟,高分求解,附代码最好

解决方案 »

  1.   

    public sealed class Singleton
        {
            public static readonly Singleton Instance = new Singleton();
            private Singleton() { }
        }
      

  2.   

    可能我没表述清楚。
    比如:有Form1、Form2两个窗体,和一个Client负责和服务端通讯的类,当Form1需要与服务器通讯时,需要实例化Client,才能使用Client的方法,当Form2与服务器通讯的时候又要实例化后,才能调用方法,请问如何能在程序Main方法时就实例化Client,form1和Form2无需实例化,直接调用具体方法即可!!
    谢谢,求教了!
      

  3.   

    你的Client类有实例特征的字段、方法和属性吗?如果有,你就应该用到的时候实例化,如果没有,即它只是包装了一些通用方法,你应该让Client是静态类(staic class),所有地方直接用静态类的类方法。当然,如果只是某些方法你希望是公用不变的方法,那么类仍然是普通类,即大部分是实例方法,把公用不变的方法标记为静态方法(static method)。
      

  4.   


    public class Singleton
        {
            private static Singleton instance;
            private static object my_lock = new object();        private Singleton()
            {        }        public static Singleton GetInstance()
            {
                if (instance == null)
                {
                    lock (my_lock)
                    {
                        if (instance == null)
                        {
                            instance = new Singleton();
                        }
                    }
                }
                return instance;
            }
            public void DoYourWork()
            {
                //Todo: 这里写你自己的功能逻辑代码即可
            }
        }这是懒汉式的单例模式,楼上的 SocketUpEx ,其实已经给出了方案了,这里只是给你详细化了,解决了多线程安全的问题,如果不需要,直接去掉lock相关的代码即可;
    下面是测试的代码class Program
        {
            static void Main(string[] args)
            {
                Singleton myinstant = Singleton.GetInstance();
                myinstant.DoYourWork();
                Singleton myinstant_1 = Singleton.GetInstance();
                if (myinstant == myinstant_1)
                {
                    Console.WriteLine("这里其实就是一个实例;");
                }
                Console.Read();
            }
        }