静态构造函数与构造函数区别

一:程序加载

1:静态构造函数当程序被调用的时候只会加载一次,构造函数每次调用都会被执行。

 

public class Person
    {
        public Person()
        {
            Console.WriteLine("构造函数被加载");
        }
        static Person()
        {
            Console.WriteLine("静态函数被加载");
        }

        public static void ShowName()
        {
            Console.WriteLine("中国人");
        }
        public void ShowAge()
        {
            Console.WriteLine(11);
        }

    }
View Code

 

 

二:生命周期

1:静态构造函数当程序结束以后才结束。对象生命周期当程序不在使用的时候GC自动回收。

三:应用场景

单例模式

3.1:饿汉式  由于static  特性,程序默认加就会加载,因此饿汉式缺点就是浪费资源。

 

 

 

 

我只是访问一下实例的Age属性,而public static Person Current = new Person();  当前对象还是被new 一次。

3.2:懒汉式

 

 

 

3.3 单例模式:解决了饿汉式当有两个线程同时执行的时候,还是被强制new()的问题。

 

饿汉式多线程bug

 

 

 

 

 

 

 

demo 如下

public class Person
    {
        private Person() { }
        public static int Age = 12;
        private static object currentLock = new object();
        private static Person Current;
        static Person()
        {
            Console.WriteLine("静态函数被加载");
        }
        public static Person GetInstance()
        {
            if (Current == null)
            {
                lock (currentLock)
                {
                    if (Current == null)
                    {
                        Console.WriteLine("进来了");
                        Current = new Person();
                    }
                }
                
            }
            return Current;
        }
        public static void ShowName()
        {
            Console.WriteLine("中国人");
        }
        public void ShowAge()
        {
            Console.WriteLine(11);
        }

    }

调用



 static void Main(string[] args)
        {
            Task.Factory.StartNew(() =>
            {
                Person.GetInstance().ShowAge();
            });

            Task.Factory.StartNew(() =>
            {
                Person.GetInstance().ShowAge();
            });

            

            Console.ReadKey();
        }
View Code

 

 

 

 

 

 

 

 

posted @ 2019-12-07 14:15  低调的奢华&Code  阅读(833)  评论(0)    收藏  举报