Why is TypeDescriptor.GetProperties behaving different for types and objects when working with ICustomTypeDescriptor

StackOverflow https://stackoverflow.com/questions/19221768

I created a generic class Group which implements ICustomTypeDescriptor. It just adds the properties of the generic type parameter to its own properties.

    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); 
       }
    }

Why does the following code behave different?

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

I assume this must have something to do with the fact that the properties are generated at instance time of the object. But isn't the number of attributes already defined by the used types?

Is it possible to work around this behaviour without instantiating the type?

有帮助吗?

解决方案

I assume your actual type implements ICustomTypeDescriptor; if that is the case, then only the TypeDescriptor.GetProperties(object) API can access the data, as it isn't willing to create an ad-hoc instance to get the properties (and indeed, it is pretty common that if the type implements ICustomTypeDescriptor, the properties vary per instance, so it wouldn't be useful anyway).

If you want the entire type to support this, you need to create and register a TypeDescriptionProvider. This works at a higher level, and allows custom properties to apply to the type without needing to consider an instance. The nice thing about this is that it will automatically also apply to lists etc, without needing to implement ITypedList.

So basically: research TypeDescriptionProvider.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top