创建类时的技巧,见Gou类

一般情况下,类中引用另一个类需要new一下,如Gou2类;通过Gou类的形式,可以通过属性的方式,直接.出来。

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Gou2 myclass2 = new Gou2();
            if (myclass2.a == 10)
                Console.WriteLine("chuangjian Gou2");

            if (Gou.Instance.a == 10)
                Console.WriteLine("Gou1");

            Console.ReadKey();
        }
    }

    class Gou
    {
        private static Gou m_instance;
        public static Gou Instance
        {
            get
            {
                if (m_instance == null)
                {
                    m_instance = new Gou();
                }
                return m_instance;
            }
        }
        public Gou()
        {
        }
        public int a = 10;
    }

    class Gou2
    {
        public int a = 10;
    }
}

许鸿谦
4 声望0 粉丝