gpt4 book ai didi

c# - 在 C# 中的运行时向类型化对象添加 expando 属性

转载 作者:太空狗 更新时间:2023-10-29 22:24:22 26 4
gpt4 key购买 nike

在 .net 中是否有任何方法可以在运行时将属性字典绑定(bind)到实例,即,就好像基本对象类具有如下属性:

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;
}
}

但这会阻止对象获得 GC,因为 props 集合包含一个引用。事实上,这对于我的特定用例来说还可以,因为一旦我完成了我正在使用它们的特定事情,我就可以手动清除 Prop ,但我想知道,是否有一些巧妙的方法来绑定(bind)ExpandoObject 到键,同时允许垃圾收集?

最佳答案

看看 ConditionalWeakTable<TKey, TValue> Class .

The ConditionalWeakTable<TKey, TValue> class enables language compilers to attach arbitrary properties to managed objects at run time. A ConditionalWeakTable<TKey, TValue> object is a dictionary that binds a managed object, which is represented by a key, to its attached property, which is represented by a value. The object's keys are the individual instances of the TKey class to which the property is attached, and its values are the property values that are assigned to the corresponding objects.

本质上,它是一个字典,其中的键和值都是弱引用的,只要键还活着,值就会保持事件状态。


static class ExpandoExtensions
{
private static readonly ConditionalWeakTable<object, ExpandoObject> props =
new ConditionalWeakTable<object, ExpandoObject>();

public static dynamic Props(this object key)
{
return props.GetOrCreateValue(key);
}
}

关于c# - 在 C# 中的运行时向类型化对象添加 expando 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5204382/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com