字段动态附加到托管对象

作者:追风剑情 发布于:2021-8-13 10:51 分类:C#

利用ConditionalWeakTable<TKey, TValue>使编译器可以将对象字段动态附加到托管对象。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Runtime.CompilerServices;
  7.  
  8. namespace ConsoleApp8
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. var key1 = new Key("key1");
  15. var key2 = new Key("key2");
  16. var key3 = new Key("key3");
  17.  
  18. //利用ConditionalWeakTable为对象附加字段,而不影响GC
  19. var weakTable = new ConditionalWeakTable<Key, Value>();
  20. weakTable.Add(key1, new Value());
  21. weakTable.Add(key2, new Value());
  22. weakTable.Add(key3, new Value());
  23.  
  24. var weak2 = new WeakReference(key2);
  25. key2 = null;
  26. key3 = null;
  27.  
  28. GC.Collect();
  29.  
  30. //当key被回收后,weakTable中对应的k-v也会自动移除
  31. Console.WriteLine($@"key1={key1?.ToString()??"null"}");
  32. Console.WriteLine($@"key2={key2?.ToString()??"null"}");
  33. Console.WriteLine($@"key3={key3?.ToString()??"null"}");
  34.  
  35. Console.ReadLine();
  36. }
  37.  
  38. public class Key {
  39. private readonly string _name;
  40. public Key(string name) => _name = name;
  41. public override string ToString() => _name;
  42. }
  43. public class Value {
  44. public DateTime CreationTime = DateTime.Now;
  45. public override string ToString() => CreationTime.ToShortTimeString();
  46. }
  47. }
  48. }

运行测试

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号