You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中Singleton单例实例调用的简写实现方案问询

解决方案

方案1:添加静态属性包装器(兼容性最好,无额外使用门槛)

直接修改单例类,给每个实例属性加一层静态访问代理,示例代码:

public class PlayerRuntimeVariables
{
    private PlayerRuntimeVariables()
    {
    }
    private static PlayerRuntimeVariables instance;
    
    public static PlayerRuntimeVariables Singleton
    {
        get
        {
            if (instance == null)
            {
                Debug.Log("PlayerRuntimeVariables Singleton Instance is null, creating instance");
                instance = new PlayerRuntimeVariables();
            }
            Debug.Log("PlayerRuntimeVariables Singleton returning instance");
            return instance;
        }
    }
    // 保留原有实例属性
    public float movementSpeed{ get; set; }
    
    // 新增静态代理属性
    public static float MovementSpeed 
    { 
        get => Singleton.movementSpeed; 
        set => Singleton.movementSpeed = value; 
    }
}

修改后你可以直接用 PlayerRuntimeVariables.MovementSpeed 访问,不需要再写.Singleton层级。

方案2:配合using static实现直接访问成员(和Scala导入效果完全一致)

C# 6及以上版本支持using static指令,可以直接导入静态类的所有静态成员,不需要加类名前缀:

  1. 先按方案1给属性加好静态代理
  2. 在需要调用的代码文件头部添加导入语句:
using static 你的命名空间.PlayerRuntimeVariables;
  1. 后续代码里可以直接写变量名访问,和你在Scala里的用法完全一致:
float currentSpeed = MovementSpeed;
MovementSpeed = 10f;

如果你的项目是C# 10及以上,还可以用全局using指令,在项目的GlobalUsings.cs里添加上面的using static语句,整个项目所有文件都不需要重复导入,直接就能用这些变量。

方案3:源码生成器批量生成静态代理(可选,适合属性极多的场景)

如果单例类里有几十上百个属性,手动写静态代理太麻烦,可以写一个简单的源码生成器,自动给所有公开实例属性生成对应的静态代理代码,无需手动维护。


额外优化建议

你当前的懒汉单例实现是非线程安全的,多线程环境下可能生成多个实例,可以改用Lazy<T>实现更安全的懒加载:

private static readonly Lazy<PlayerRuntimeVariables> instance = new(() => new PlayerRuntimeVariables());
public static PlayerRuntimeVariables Singleton => instance.Value;

调试日志可以放在私有构造函数里,只在实例第一次创建的时候打印,避免每次访问单例都打日志影响性能。

内容的提问来源于stack exchange,提问作者supernatural

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 01:57:02