jjzjj

ConditionalWeakTable

全部标签

c# - 压缩弱引用字典

我有一个类Foo,它有一个属性Id。我的目标是没有两个Foo实例同时具有相同的Id。所以我创建了一个工厂方法CreateFoo,它使用缓存以便为相同的Id返回相同的实例。staticFooCreateFoo(intid){Foofoo;if(!cache.TryGetValue(id,outfoo)){foo=newFoo(id);foo.Initialize(...);cache.Put(id,foo);}returnfoo;}缓存实现为字典,基于@JaredPar的BuildingaWeakReferenceHashtable:classWeakDictionarywhereTVa

c# - ConditionalWeakTable<TKey, TValue> 是否应该用于非编译器目的?

我最近遇到了ConditionalWeakTable在我搜索IDictionary的类(class)中它使用弱引用,如答案here中所建议的那样和here.有adefinitiveMSDNarticle其中介绍了该类(class)并指出:Youcanfindtheclass...intheSystem.Runtime.CompilerServicesnamespace.It’sinCompilerServicesbecauseit’snotageneral-purposedictionarytype:weintendforittoonlybeusedbycompilerwriters.