Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Singleton #83

Open
sunshin5 opened this issue Jun 9, 2020 · 0 comments
Open

Singleton #83

sunshin5 opened this issue Jun 9, 2020 · 0 comments

Comments

@sunshin5
Copy link

sunshin5 commented Jun 9, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant