Agregar propiedades en tiempo de ejecución
Tengo una clase que el programador puede usar para agregar dinámicamente nuevas propiedades. Para eso implementa laICustomTypeDescriptor
para poder anularGetProperties()
método.
public class DynamicProperty
{
public object Value { get; set; }
public Type Type { get; set; }
public string Name { get; set; }
public Collection<Attribute> Attributes { get; set; }
}
public class DynamicClass : ICustomTypeDescriptor
{
// Collection to code add dynamic properties
public KeyedCollection<string, DynamicProperty> Properties
{
get;
private set;
}
// ICustomTypeDescriptor implementation
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
// Properties founded within instance
PropertyInfo[] instanceProps = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
// Fill property collection with founded properties
PropertyDescriptorCollection propsCollection =
new PropertyDescriptorCollection(instanceProps.Cast<PropertyDescriptor>().ToArray());
// Fill property collection with dynamic properties (Properties)
foreach (var prop in Properties)
{
// HOW TO?
}
return propsCollection;
}
}
¿Es posible iterar sobre la lista de Propiedades para agregar cada propiedad aPropertyDescriptorCollection
?
ásicamente quiero que el programador pueda agregar unDynamicProperty
a una colección que será manejada porGetProperties
. Algo como
new DynamicClass()
{
Properties = {
new DynamicProperty() {
Name = "StringProp",
Type = System.String,
Value = "My string here"
},
new DynamicProperty() {
Name = "IntProp",
Type = System.Int32,
Value = 10
}
}
}
Ahora esosProperties
se establecería en propiedades de instancia siempre queGetProperties
se llama. ¿Estoy pensando de esta manera?