How to add property at runtime in a class already created C #

2

I need to add properties in the GridDataSourceBase class at runtime, can anyone help me how to do this?

public class GridDataSourceBase : IGridDataSource
{
    public long Handle { get; set; }
}
    
asked by anonymous 11.07.2017 / 01:17

1 answer

0

One way is to use ExpandoObject .

dynamic objeto = new ExpandoObject();
objeto.Propriedade = 1;

You will most likely have to copy the properties of the old object to this object. You can do this as follows:

public static class DynamicExtensions
{
    public static dynamic ToDynamic(this object value)
    {
        IDictionary<string, object> expando = new ExpandoObject();

        var props = TypeDescriptor.GetProperties(value.GetType());
        foreach (PropertyDescriptor property in props)
            expando.Add(property.Name, property.GetValue(value));

        return expando as ExpandoObject;
    }
}

var tuple = Tuple.Create(1, 1);
var newTuple = tuple.ToDynamic();
newTuple.Item3 = 1;

Source

    
21.09.2017 / 16:31