字段动态附加到托管对象

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

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;

namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args)
        {
            var key1 = new Key("key1");
            var key2 = new Key("key2");
            var key3 = new Key("key3");

            //利用ConditionalWeakTable为对象附加字段,而不影响GC
            var weakTable = new ConditionalWeakTable<Key, Value>();
            weakTable.Add(key1, new Value());
            weakTable.Add(key2, new Value());
            weakTable.Add(key3, new Value());

            var weak2 = new WeakReference(key2);
            key2 = null;
            key3 = null;

            GC.Collect();

            //当key被回收后,weakTable中对应的k-v也会自动移除
            Console.WriteLine($@"key1={key1?.ToString()??"null"}");
            Console.WriteLine($@"key2={key2?.ToString()??"null"}");
            Console.WriteLine($@"key3={key3?.ToString()??"null"}");

            Console.ReadLine();
        }

        public class Key {
            private readonly string _name;
            public Key(string name) => _name = name;
            public override string ToString() => _name;
        }
        public class Value {
            public DateTime CreationTime = DateTime.Now;
            public override string ToString() => CreationTime.ToShortTimeString();
        }
    }
}

运行测试

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号