C#单例

一、懒加载

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; }
}
posted @ 2024-01-31 15:12  xuxuzhaozhao  阅读(5)  评论(0编辑  收藏  举报