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

后端 未结 2 1165
情话喂你
情话喂你 2020-12-15 01:54

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 IDiction         


        
2条回答
  •  渐次进展
    2020-12-15 02:17

    Have a look at the ConditionalWeakTable Class.

    The ConditionalWeakTable class enables language compilers to attach arbitrary properties to managed objects at run time. A ConditionalWeakTable 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 props =
            new ConditionalWeakTable();
    
        public static dynamic Props(this object key)
        { 
            return props.GetOrCreateValue(key);       
        } 
    }
    

提交回复
热议问题