Skip to content

Singleton #83

@sunshin5

Description

@sunshin5
public sealed class Singleton4
{
    private Singleton4()
    {
        Console.WriteLine("An instance of Singleton4 is created.");
    }

    public static void Print()
    {
        Console.WriteLine("Singleton4 Print");
    }

    private static Singleton4 instance = new Singleton4();
    public static Singleton4 Instance
    {
        get
        {
            return instance;
        }
    }
}

public sealed class Singleton5
{
    Singleton5()
    {
        Console.WriteLine("An instance of Singleton5 is created.");
    }

    public static void Print()
    {
        Console.WriteLine("Singleton5 Print");
    }

    public static Singleton5 Instance
    {
        get
        {
            return Nested.instance;
        }
    }

    class Nested
    {
        static Nested()
        {
        }

        internal static readonly Singleton5 instance = new Singleton5();
    }
}

class Program
{
    static void Main(string[] args)
    {
        // 也会打印An instance of Singleton4 is created.
        Singleton4.Print();

        // 不会打印An instance of Singleton5 is created.
        Singleton5.Print();
        Console.WriteLine("Finished!!!");
    }
}

实测Netcore下Singleton4也不会打印An instance of Singleton4 is created;但是NetFrameWork也会打印An instance of Singleton4 is created.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions