X3

RedSky

导航

C# ConditionalWeakTable扩展属性通用类

代码:

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; private set; } = new ConditionalWeakTable<object, Dictionary<string, object>>();

        public Dictionary<string, object>? this[object key]
        {
            get
            {
                if (key == null) return null;
                Dictionary<string, object>? v;
                bool s = Table.TryGetValue(key, out v);
                return v;
            }
        }

        public void SetValue(object key, string propertyName, object value)
        {
            var kv = Instance[key];

            if (kv == null)
            {
                var dict = new Dictionary<string, object>
                    {
                        { propertyName, value }
                    };
                Instance.Table.Add(key, dict);
            }
            else if(kv.ContainsKey(propertyName))
                kv[propertyName] = value;
            else
                kv.Add(propertyName, value);
        }

        public object? GetValue(object key, string propertyName)
        {
            var kv = Instance[key];

            if (kv == null)
                return null;
            object? r;
            kv.TryGetValue(propertyName, out r);
            return r;
        }
    }

 

 

使用参考:

    public interface IImage { }
    public class MyImage : IImage { }
    public static class IImageExtension
    {
        public static void SetPath(this IImage image, string path)
        {
            AttachedProperty.Instance.SetValue(image, "Path", path);
        }

        public static string? GetPath(this IImage image)
        {
            return AttachedProperty.Instance.GetValue(image, "Path")?.ToString();
        }
    }

 

posted on 2023-10-16 18:03  HotSky  阅读(31)  评论(0编辑  收藏  举报