[Unity]C#中的泛型单例(Singleton)

4 篇文章 1 订阅

目录

一.引言

二.代码样例

1.where说明:

三.Unity中的运用

1.编写单例子类CentralBank脚本

四.关于泛型如Singleton的补充说明:


一.引言

在C#中需要批量创生单例类时,一个个的写类实在时太累了.于是为了省力,我们要写一个父类,当继承了这个父类就可以成为单例类.

二.代码样例

using System;
using System.Collections;
using System.Collections.Generic;





public class Singleton<T> where T : Singleton<T>,new()
{   //static前缀使得可以通过类名.属性名来访问该属性
    private static T instance = null;
    public static T Instance
    {   //只有get方法没有set方法,意味Instance对其他类为只读
        get
        {   //如果instance为空,则重新初始化instance为指向T类实例的指针
            if (instance == null)
            {
                instance = new T();
            }
            //否则返回唯一的instance属性
            return instance;
        }
    }
}

1.where说明:

​
public class Singleton<T> where T : Singleton<T>,new()

​

where T : class意味着对T的类型约束,即T必须为class类或者class类的子类

where T: new()意味着该类型必须具有无参数构造函数。有了这个约束将允许这样初始化T类型的实例

T instance = new T();

否则不能这样初始化一个实例

用逗号结合两者得到

where T : class,new()

//此例中为
where T : Singleton<T>,new()

三.Unity中的运用

如我们要初始化一个中央银行,中央银行只能存在一个,方便统一管理所有人的数据

则首先写一个 Singleton的父类脚本

注意:1.这里没有在where后添加new(),因为我们使用instance=(T)this来初始化.

2.含有static的属性在类被创建时就被储存在静态储存区中,而不是在类被实体化时被创建,并且全局只创建一次,也就是只有一份.

3.只有当Singleton<T>的子类第一个对象被初始化时会改变 子类名.instance 的值为指向该对象指针,之后的对象初始化时会自动销毁.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Singleton<T> :MonoBehaviour where T : Singleton<T>
{
    private static T instance;

    public static T Instance
    {
        //只能被访问,不能被改写
        get { return instance; }
        
    
    }



    //protected意味只能被该类或者子类访问
    //virtual意味着子类可以改写该方法
    //Awake在脚本对象创建后立刻调用

    protected virtual void Awake()
    {
        //如果有本类instance存在(代表已经存在一个对象),则销毁该对象
        //否则instance指向该对象
        if (instance != null)
            Destroy(instance);
        else
            instance = (T)this;

    }




}

1.编写单例子类CentralBank脚本

public class CentralBank:Singleton<CentralBank>
{

}

四.关于泛型如Singleton<T>的补充说明:

http://t.csdn.cn/LY2ak

希望能有帮助

  • 7
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值