对象数据关联扩展
2016-08-01 本文已影响72人
2b75747cf703
经常会在代码中进行数据关联,比如某张图片点击要打开某个链接。
写了一个扩展,任何对象可以和任何数据关联。
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);
}
}
}