在 C# 中运行时向类型化对象添加 Expando 属性
.net 中是否有任何方法可以在运行时将属性字典绑定到实例,即,就好像基对象类具有如下属性:
public IDictionary Items { get; }
我提出了一个涉及静态字典和扩展方法的解决方案,
void Main()
{
var x = new object();
x.Props().y = "hello";
}
static class ExpandoExtension {
static IDictionary<object, dynamic> props = new Dictionary<object, dynamic>();
public static dynamic Props(this object key)
{
dynamic o;
if (!props.TryGetValue(key, out o)){
o = new ExpandoObject();
props[key] = o;
}
return o;
}
}
但这会停止由于 props 集合持有引用,因此对象不会被 GC 回收。事实上,这对于我的特定用例来说是可以的,因为一旦我完成了我正在使用它们的特定任务,我就可以手动清除这些道具,但我想知道,是否有一些巧妙的方法来绑定这些道具ExpandoObject 到键同时允许垃圾回收?
Is there any way in .net to bind a dictionary of properties to an instance at runtime, i.e., as if the base object class had a property like:
public IDictionary Items { get; }
I have come up with a solution involving a static dictionary and extension method
void Main()
{
var x = new object();
x.Props().y = "hello";
}
static class ExpandoExtension {
static IDictionary<object, dynamic> props = new Dictionary<object, dynamic>();
public static dynamic Props(this object key)
{
dynamic o;
if (!props.TryGetValue(key, out o)){
o = new ExpandoObject();
props[key] = o;
}
return o;
}
}
but this stops the objects from getting GC'd as the the props collection holds a reference. In fact, this is just about ok for my particular use case, as I can clear the props down manually once I've finished with the particular thing I'm using them for, but I wonder, is there some cunning way to tie the ExpandoObject to the key while allowing garbage collection?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 ConditionalWeakTable类 。
本质上,它是一个字典,其中键和值都是弱引用的,并且只要键还活着,值就保持活动状态。
Have a look at the ConditionalWeakTable<TKey, TValue> Class.
Essentially it's a dictionary where both the keys and the values are weakly referenced, and a value is kept alive as long as the key is alive.
您可以使用 WeakReference 来引用对象,以便它们可以仍然会被垃圾收集。不过,您仍然需要手动清理字典,因为对象本身会被破坏。
You could use a WeakReference to reference the objects so that they can still be garbage collected. You'll still have to clean up your dictionary by hand though, as the objects themselves are destroyed.