WeakReference

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);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值