adding expando properties to a typed object at runtime in c#(在 C# 中在运行时向类型化对象添加扩展属性)
问题描述
.net 中是否有任何方法可以在运行时将属性字典绑定到实例,即,就好像基对象类具有如下属性:
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;
}
}
但这会阻止对象进行 GC,因为 props 集合包含一个引用.事实上,这对于我的特定用例来说还可以,因为一旦我完成了我正在使用它们的特定事物,我就可以手动清除道具,但我想知道,是否有一些巧妙的方法来绑定ExpandoObject 到 key 同时允许垃圾回收吗?
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?
推荐答案
看看 ConditionalWeakTable
ConditionalWeakTable
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.
本质上它是一个字典,其中键和值都被弱引用,只要键还活着,值就会保持活动状态.
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.
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# 中在运行时向类型化对象添加扩展属性


- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01