public class SingletonObject { public string name { get; set; } public SingletonObject() { name=Guid.NewGuid().ToString(); } public static readonly object lock_obj=new object(); public static SingletonObject singletonObject; public static SingletonObject CreateSingletion() { if (singletonObject == null) { lock (lock_obj) { if (singletonObject == null) singletonObject = new SingletonObject(); } } return singletonObject; } }
调用
var singleton = SingletonObject.CreateSingletion(); var singleton2 = SingletonObject.CreateSingletion(); Console.WriteLine(singleton.name); Console.WriteLine(singleton2.name);
标签:name,lock,模式,static,singletonObject,单例,public,SingletonObject From: https://www.cnblogs.com/daiwk/p/18108436