我有一个类,程序员可以使用它来动态添加新属性。为此,它实现了
ICustomTypeDescriptor
接口并重写了 GetProperties()
方法。
我有一个类,程序员可以使用它来动态添加新属性。为此,它实现了 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
}
}
}
现在,每当调用GetProperties
时,这些属性
将被设置为实例属性。我这样想是否正确?
propertyType
是属性本身的类型,对吗?那componentType
又是什么呢?它是指属性所在对象的类型吗? - JoaopropertyType
是动态属性的类型。如果您有一个名为Count
的动态整数属性,则其类型应为typeof(int)
。componentType
是具有动态属性的类的类型,例如typeof(MyDynamicPropertyClass)
。 - Rick Sladkeyvar
),我可以确保使用GetProperties()
来访问所述属性吗? - Joao