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

目录

一.引言

二.代码样例

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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值