对象数据关联扩展

作者: 2b75747cf703 | 来源:发表于2016-08-01 10:23 被阅读72次

    经常会在代码中进行数据关联,比如某张图片点击要打开某个链接。
    写了一个扩展,任何对象可以和任何数据关联。

    using System.Collections.Generic;
    using UnityEngine;
    
    namespace Babybus.Framework.ExtensionMethods
    {
        public static class ObjectExtension
        {
            private static Dictionary<object, Dictionary<string, object>> dictionary = new Dictionary<object, Dictionary<string, object>>();
    
            public static bool HasData(this object obj, string key)
            {
                return dictionary.ContainsKey(obj);
            }
    
            public static void SetData(this object obj, string key, object value)
            {
                if (!dictionary.ContainsKey(obj))
                    dictionary.Add(obj, new Dictionary<string, object>());
    
                dictionary[obj][key] = value;
            }
    
            public static T GetData<T>(this object obj, string key, T defaultValue = default(T))
            {
                if (!dictionary.ContainsKey(obj))
                    return defaultValue;
    
                return (T)dictionary[obj][key];
            }
    
            public static void DeleteData(this object obj, string key)
            {
                if (!dictionary.ContainsKey(obj))
                    return;
    
                var data = dictionary[obj];
                if (data.ContainsKey(key))
                    data.Remove(key);
            }
    
            public static void DeleteAll(this object obj)
            {
                if (dictionary.ContainsKey(obj))
                    dictionary.Remove(obj);
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:对象数据关联扩展

        本文链接:https://www.haomeiwen.com/subject/wnuxsttx.html