相关疑难解决方法(0)

压缩WeakReference词典

我有一个带有属性Id的Foo类.我的目标是同时没有两个具有相同IdFoo实例.

所以我创建了一个工厂方法CreateFoo,它使用缓存来为同一个Id返回相同的实例.

static Foo CreateFoo(int id) {
    Foo foo;
    if (!cache.TryGetValue(id, out foo)) {
        foo = new Foo(id);
        foo.Initialize(...);
        cache.Put(id, foo);
    }
    return foo;
}
Run Code Online (Sandbox Code Playgroud)

缓存实现为Dictionary <TKey,WeakReference>,基于@JaredParBuilding a WeakReference Hashtable:

class WeakDictionary<TKey, TValue> where TValue : class {
    private readonly Dictionary<TKey, WeakReference> items;
    public WeakDictionary() {
        this.items = new Dictionary<TKey, WeakReference>();
    }
    public void Put(TKey key, TValue value) {
        this.items[key] = new WeakReference(value);
    }
    public …
Run Code Online (Sandbox Code Playgroud)

c# weak-references .net-4.0

16
推荐指数
2
解决办法
5581
查看次数

标签 统计

.net-4.0 ×1

c# ×1

weak-references ×1