在 C# 中在运行时向类型化对象添加扩展属性

adding expando properties to a typed object at runtime in c#(在 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类使语言编译器能够在运行时将任意属性附加到托管对象.ConditionalWeakTable<TKey, TValue>object 是一个字典,它将一个由键表示的托管对象绑定到它的附加属性,该属性由一个值表示.对象的键是属性附加到的 TKey 类的各个实例,其值是分配给相应对象的属性值.

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# 中在运行时向类型化对象添加扩展属性

基础教程推荐