首页 > Windows开发 > 详细

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

时间:2020-08-24 16:48:31      阅读:92      评论:0      收藏:0      [点我收藏+]

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

代码:

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# 静态单例的几种使用创建方法

原文:https://www.cnblogs.com/kexiong/p/13554448.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!