using System; using System.Collections.Generic; namespace WK { /// /// 实现此接口重置回收对象的成员值 /// public interface IRcycle { void Release(); } public class Recycle where T : IRcycle, new() { private List cachedNodeList; private int maxCapacity; public Recycle(int initCapacity, int maxCapacity) { this.maxCapacity = maxCapacity; if (cachedNodeList == null) { cachedNodeList = new List(initCapacity); for (int i = 0; i < initCapacity; ++i) { cachedNodeList.Add(new T()); } } } public T GetUnusedNode() { if (cachedNodeList.Count > 0) { // remove and return last node int i = cachedNodeList.Count - 1; T t = cachedNodeList[i]; cachedNodeList.RemoveAt(i); return t; } return new T(); } //回收对象并将原引用置为初始值(0或null) public bool ReleaseNode(ref T t) { if (t == null) return false; T refT = t; t = default(T); if (cachedNodeList.Count > maxCapacity) return false; if (cachedNodeList.Contains(refT)) { LogHelper.LogError("重复回收"); return false; } refT.Release(); cachedNodeList.Add(refT); return true; } } }