C# ConditionalWeakTable通用类

发布时间 2023-10-16 18:06:22作者: HotSky
    public class AttachedProperty
    {
        static AttachedProperty? instance = null;
        static object instanceLock = new object();
        public static AttachedProperty Instance
        {
            get
            {
                if (instance == null)
                    lock (instanceLock)
                    {
                        if (instance == null)
                            instance = new AttachedProperty();
                    }
                return instance;
            }
        }

        public ConditionalWeakTable<object, Dictionary<string, object>> Table { get; set; } = new ConditionalWeakTable<object, Dictionary<string, object>>();

        public Dictionary<string, object>? this[object key]
        {
            get
            {
                if (key == null) return null;
                var v = Table.FirstOrDefault(f => f.Key == key);
                return v.Value;
            }
        }
    }

使用方法:

    public interface IImage { }
    public class MyImage : IImage { }
    public static class IImageExtension
    {
        public static void SetPath(this IImage image, string path)
        {
            var kv = AttachedProperty.Instance[image];
            
            if (kv == null)
            {
                var dict = new Dictionary<string, object>
                    {
                        { "Path", path }
                    };
                AttachedProperty.Instance.Table.Add(image, dict);
            }
            else
            {
                kv.Add("Path", path);
            }
        }

        public static string? GetPath(this IImage image)
        {
            var kv = AttachedProperty.Instance[image];

            if (kv != null)
                return kv["Path"]?.ToString();
            return null;
        }
    }