adding expando properties to a typed object at runtime in c#

荒凉一梦 提交于 2019-11-28 22:04:51

Have a look at the 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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!