一、懒加载
public sealed class SingletonDemo
{
private SingletonDemo()
{
}
private static readonly Lazy<SingletonDemo> Lazy = new(() => new SingletonDemo());
public static SingletonDemo Instance => Lazy.Value;
}
二、单例泛型继承
public abstract class SpSingleton<T> where T : class
{
private static readonly Lazy<T> Lazy = new(() =>
{
var ctors = typeof(T).GetConstructors(
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public);
if (ctors.Length != 1)
throw new InvalidOperationException($"Type {typeof(T)} must have exactly one constructor.");
var ctor = ctors.SingleOrDefault(c => !c.GetParameters().Any() && c.IsPrivate);
if (ctor == null)
throw new InvalidOperationException($"The constructor for {typeof(T)} must be private and take no parameters.");
return (T)ctor.Invoke(null);
}, true);
public static T Instance => Lazy.Value;
}
/// <summary>
/// Test
/// </summary>
public class SpSingletonTest : SpSingleton<SpSingletonTest>
{
private SpSingletonTest()
{
GuidString = Guid.NewGuid().ToString();
}
public string GuidString { get; set; }
}
标签:Lazy,一次,C#,private,static,单例,new,SingletonDemo,public
From: https://www.cnblogs.com/xuxuzhaozhao/p/17999309