我有一个程序员可以用来动态添加新属性的类。为此,它实现了ICustomTypeDescriptor
以便能够覆盖GetProperties()
方法。在运行时添加属性
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;
}
}
是否可以遍历属性列表中的每个属性添加到PropertyDescriptorCollection
?
基本上我希望程序员能够将DynamicProperty
添加到将由GetProperties
处理的集合中。喜欢的东西:
new DynamicClass()
{
Properties = {
new DynamicProperty() {
Name = "StringProp",
Type = System.String,
Value = "My string here"
},
new DynamicProperty() {
Name = "IntProp",
Type = System.Int32,
Value = 10
}
}
}
现在那些Properties
将设置好的,以实例的属性,只要GetProperties
被调用。我是否认为这是正确的方式?
'propertyType'是属性本身的类型吧?那么componentType呢?它是属性所在的对象的类型? – Joao 2011-05-29 07:32:54
'propertyType'是动态属性的类型。如果你有一个名为'Count'的动态整数属性,它会是'typeof(int)'。 'componentType'是具有动态属性的类的类型,例如'typeof运算(MyDynamicPropertyClass)'。 – 2011-05-29 07:37:30
还有一个问题。这样,如果以前通过'Properties'列表添加的属性是动态访问的(例如使用'var'),我可以确定使用'GetProperties()'来访问所述属性吗? – Joao 2011-05-29 07:40:31