对象池模板类(基类)和c#手动回收

一、对象池
在一款游戏中,我们不止有一个对象池,为了方便对对象池的创建,由此写了一个模板类。当然,也可以实现全功能的对象池,不管什么类型都可以。在此就不在阐述了。

在此模板类中,使用了委托,系统自带的委托函数,以及堆栈的使用。

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

public class ObjectPool<T> where T : new()
{
//最好改为只读的
    private   Stack<T> m_Stack = new Stack<T>(); //使用栈进行创建。
    private  UnityAction<T> m_ActionOnGet; 
    private   UnityAction<T> m_ActionOnRelease;

    public int countAll { get; private set; } 	//池中对象的总个数
    public int countActive { get { return countAll - countInactive; } }	//活跃的对象
    public int countInactive { get { return m_Stack.Count; } }	//失活的对象,即可以进行回收的对象

 	public T CreateObject()
    {
        T element;
        if (m_Stack.Count == 0)
        {
            element = new T();
            countAll++;
        }
        else
        {
            element = m_Stack.Pop();
        }
        if (m_ActionOnGet != null)
            m_ActionOnGet(element);
        return element;
    }

    public ObjectPool(UnityAction<T> actionOnGet, UnityAction<T> actionOnRelease)  	
    {
        m_ActionOnGet = actionOnGet;
        m_ActionOnRelease = actionOnRelease;
    }

  
    public void Release(T element)
    {
        if (m_Stack.Count > 0 && ReferenceEquals(m_Stack.Peek(), element))
        //输出错误日志,可以使用自己写的日志进行输出
            Debug.LogError("Internal error. Trying to destroy object that is already released to pool."); 	
        if (m_ActionOnRelease != null)
            m_ActionOnRelease(element);
        m_Stack.Push(element);	//弹栈
    }
}


二、C#手动回收
在Net中,由GC垃圾回收线程掌握对象资源的释放,程序员无法掌控析构函数的调用时机。对于一些非托管资源,比如数据库链接对象等,需要实现IDisposable接口进行手动的垃圾回收。
在此模板类中,使用了委托,系统自带的委托函数,以及堆栈的使用。

    
    //
    // 摘要:
    //     Defines a method to release allocated resources.
    [ComVisible(true)]
    public interface IDisposable
    {
        //
        // 摘要:
        //     Performs application-defined tasks associated with freeing, releasing, or resetting
        //     unmanaged resources.
        void Dispose();
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Gxy_w

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值