WeakReference
表示弱引用,即在引用对象的同时仍然允许通过垃圾回收来回收该对象。
如果您需要该对象,仍可以获得对它的强引用并防止它被回收。
Target
属性 WeakReference 对象是表示数据的字节数组中的对象。
using System;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour {
void Start(){
int cacheSize = 50;
System.Random r = new System.Random();
Cache c = new Cache(cacheSize);
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour {
void Start(){
int cacheSize = 50;
System.Random r = new System.Random();
Cache c = new Cache(cacheSize);
string DataName = "";
GC.Collect(0);
for (int i = 0; i < c.Count; i++){
int index = r.Next(c.Count);
DataName = c[index].Name;
}
double regenPercent = c.RegenerationCount / (double)c.Count;
Debug.LogErrorFormat("Cache size: {0}, Regenerated: {1:P2}", c.Count, regenPercent);
}
}
public class Cache
{
static Dictionary<int, WeakReference> _cache;
int regenCount = 0;//跟踪对象重新生成的次数
public Cache(int count)
{
_cache = new Dictionary<int, WeakReference>();
for (int i = 0; i < count; i++){
_cache.Add(i, new WeakReference(new Data(i), false));
}
}
public int Count { get { return _cache.Count; } }
public int RegenerationCount { get { return regenCount; } }
public Data this[int index]
{
get {
Data d = _cache[index].Target as Data;
if (d == null)
{
Debug.LogErrorFormat("Regenerate object at {0}: Yes", index);
d = new Data(index);
_cache[index].Target = d;
regenCount++;
}
else
{
Debug.LogErrorFormat("Regenerate object at {0}: No", index);
}
return d;
}
}
}
public class Data
{
private byte[] _data;
private string _name;
public Data(int size)
{
_data = new byte[size * 1024];
_name = size.ToString();
}
public string Name { get { return _name; } }
}