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# 中在运行时向类型化对象添加扩展属性
基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何激活MC67中的红灯 2022-01-01