C# 静态单例的几种使用创建方法

静态单例的几种使用创建方法

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 静态单例
{
public class StudentManager
{
private static readonly StudentManager instance = new StudentManager();
public static StudentManager Instance()
{
return instance;
}

StudentManager()
{ }

public void Show()
{
Console.WriteLine("这是一个学生管理的静态单例1");
}
}

public class StudentManager2
{
private static StudentManager2 instance = null;

public static StudentManager2 Instance()
{
return instance;
}

static StudentManager2()
{
if (instance == null)
{
instance = new StudentManager2();
}
}

public void Show()
{
Console.WriteLine("这是一个学生管理的静态单例2");
}
}

public class StudentManager3
{
private static StudentManager3 instance;

public static StudentManager3 Instance()
{
return instance ?? (instance = new StudentManager3());
}

StudentManager3()
{

}

public void Show()
{
Console.WriteLine("这是一个学生管理的静态单例3");
}
}

public class StudentManager4
{
public static readonly StudentManager4 Instance = new StudentManager4();

StudentManager4()
{

}

public void Show()
{
Console.WriteLine("这是一个学生管理的静态单例4");
}
}

public class StudentManager5
{
private static readonly StudentManager5 instance = new StudentManager5();

public static StudentManager5 Instance
{
get { return instance; }
}

StudentManager5()
{

}

public void Show()
{
Console.WriteLine("这是一个学生管理的静态单例5");
}
}
}

 

C# 静态单例的几种使用创建方法

上一篇:windows查看连接过wifi的密码


下一篇:Win10微软拼音关闭Ctrl+Shift+B快捷键