为什么TypeDescriptor.GetProperties在使用ICustomTypeDescriptor时对类型和

本文关键字:类型 ICustomTypeDescriptor TypeDescriptor GetProperties 为什么 | 更新日期: 2023-09-27 18:34:07

我创建了一个实现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

我认为这肯定与属性是在对象的实例时生成的这一事实有关。但是,使用的类型不是已经定义了属性的数量吗?

是否可以在不实例化类型的情况下解决此行为?

为什么TypeDescriptor.GetProperties在使用ICustomTypeDescriptor时对类型和

我假设您的实际类型实现了ICustomTypeDescriptor;如果是这种情况,那么只有TypeDescriptor.GetProperties(object) API可以访问数据,因为它不愿意创建一个临时实例来获取属性(事实上,如果类型实现ICustomTypeDescriptor,则属性因实例而异,因此无论如何都不会有用)。

如果希望整个类型都支持此功能,则需要创建并注册一个TypeDescriptionProvider。这在更高级别工作,并允许自定义属性应用于类型,而无需考虑实例。这样做的好处是它也会自动应用于列表等,而无需实现ITypedList

所以基本上:研究TypeDescriptionProvider.