Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 单例

作者:颠沛流离的伤   发布日期:2025-04-30   浏览:18

using System;

public class Singleton
{
    // 私有静态变量用于保存类的唯一实例
    private static Singleton uniqueInstance;

    // 私有构造函数,防止外部实例化
    private Singleton() { }

    // 公有静态方法,提供全局访问点
    public static Singleton GetInstance()
    {
        if (uniqueInstance == null)
        {
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }

    // 示例方法
    public void DoSomething()
    {
        Console.WriteLine("Doing something...");
    }
}

// 使用示例
class Program
{
    static void Main(string[] args)
    {
        Singleton singleton = Singleton.GetInstance();
        singleton.DoSomething();
    }
}

解释说明:

  1. 私有静态变量private static Singleton uniqueInstance; 用于保存类的唯一实例。
  2. 私有构造函数private Singleton() 防止外部通过构造函数创建实例。
  3. 公有静态方法public static Singleton GetInstance() 提供全局访问点,确保只有一个实例存在。
  4. 线程安全问题:此代码示例未处理多线程环境下的并发问题。如果需要线程安全的单例模式,可以考虑使用双重检查锁定或静态初始化等方式。

上一篇:c# unsafe

下一篇:c#winform

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# if else

c# rtsp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站