我创建了一个实现ICustomTypeDescriptor的泛型类组。它只是将泛型类型参数的属性添加到自己的属性中。
private void InitializeDisplayedProperties()
{
_DisplayedProperties.Add(TypeDescriptor.GetProperties(typeof(Group<T>))["LastItem"]);
_DisplayedProperties.Add(TypeDescriptor.GetProperties(typeof(Group<T>))["GroupId"]);
_DisplayedProperties.Add(TypeDescriptor.GetProperties(typeof(Group<T>))["Count"]);
foreach (PropertyDescriptor myDescr in TypeDescriptor.GetProperties(typeof(T)))
{
_DisplayedProperties.Add(myDescr);
}
}为什么下面的代码表现不同?
TypeDescriptor.GetProperties(typeof(Group<IGroupedObject>)).Count //Returns 3 Items of Group only
TypeDescriptor.GetProperties(new Group<IGroupedObject>()).Count //Returns all 31 Items of Group and generic type parameter我假定这一定与在对象的实例时生成属性这一事实有关。但是,使用的类型不是已经定义了属性的数量吗?
在不实例化类型的情况下,可以绕过这种行为吗?
发布于 2013-10-07 10:02:22
我假设您的实际类型实现了ICustomTypeDescriptor;如果是这样的话,那么只有TypeDescriptor.GetProperties(object) API可以访问数据,因为它不愿意创建一个临时实例来获取属性(实际上,如果该类型实现了ICustomTypeDescriptor,那么每个实例的属性都会有所不同,因此无论如何都不会有用)。
如果希望整个类型支持此功能,则需要创建和注册一个TypeDescriptionProvider。这可以在更高的级别上工作,并且允许自定义属性应用于类型,而不需要考虑实例。这方面的好处是,它也将自动应用于列表等,而不需要实现ITypedList。
所以基本上:研究TypeDescriptionProvider。
https://stackoverflow.com/questions/19221768
复制相似问题