** 完整答案已编辑 ** 属性保存在字典中,该字典使用对对象的弱引用作为键,并使用字符串-对象对的字典来存储属性及其值。
要设置、获取或删除对象的属性,请在字典中的弱引用中搜索该对象。
可以有两种方法来处理未使用的属性:
- 检查弱引用的 IsAlive,如果为 false,则删除字典中的条目
- 在“可扩展”对象中实现 IDisposable 并调用一个扩展方法来删除正在释放的对象上的属性。
我在示例代码中包含了一个可选的 using 块,以便您可以调试并查看 Dispose 如何调用RemoveProperties
扩展方法。这当然是可选的,并且该方法将在对象被 GC 时调用。
该想法的工作示例,使用 WeakReference、静态字典和 IDisposable。
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
using (PropertyLessClass plc = new PropertyLessClass())
{
plc.SetProperty("age", 25);
plc.SetProperty("name", "John");
Console.WriteLine("Age: {0}", plc.GetProperty("age"));
Console.WriteLine("Name: {0}", plc.GetProperty("name"));
}
Console.ReadLine();
}
}
}
public class PropertyLessClass : IDisposable
{
public void Dispose()
{
this.DeleteProperties();
}
}
public static class PropertyStore
{
private static Dictionary<WeakReference, Dictionary<string, object>> store
= new Dictionary<WeakReference, Dictionary<string, object>>();
public static void SetProperty(this object o, string property, object value)
{
var key = store.Keys.FirstOrDefault(wr => wr.IsAlive && wr.Target == o);
if (key == null)
{
key = new WeakReference(o);
store.Add(key, new Dictionary<string, object>());
}
store[key][property] = value;
}
public static object GetProperty(this object o, string property)
{
var key = store.Keys.FirstOrDefault(wr => wr.IsAlive && wr.Target == o);
if (key == null)
{
return null; // or throw Exception
}
if (!store[key].ContainsKey(property))
return null; // or throw Exception
return store[key][property];
}
public static void DeleteProperties(this object o)
{
var key = store.Keys.FirstOrDefault(wr => wr.IsAlive && wr.Target == o);
if (key != null)
{
store.Remove(key);
}
}
}