Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Getting an object's actual TypeDescriptionProvider or TypeDescriptor

Tags:

c#

I realise that this is an unusual issue, but:

I have created a custom TypeDescriptionProvider that can store and return different TypeDescriptors based on the requested object Type. What I have noticed however is that regardless of the TypeDescriptionProvider associated with a Type (be-it custom or default) the TypeDescriptor.GetProvider() always returns an (internal class) System.ComponentModel.TypeDescriptor.TypeDescriptionNode object (some kind of wrapper around the actual TypeDescriptionProvider). In turn calling GetTypeDescriptor() on this object always returns a System.ComponentModel.TypeDescriptor.TypeDescriptionNode.DefaultTypeDescriptor object (another wrapper) and stranger still does not call the TypeDescriptionProvider's actual GetTypeDescriptor() method.

Does this mean that there is really no way to get back either an object's actual TypeDescriptionProvider or its TypeDescriptor from its provider? The methods to return the classname, properties, etc. still work as expected on the DefaultTypeDescriptor, but I am unable to compare or find out if two objects use the same TypeDescriptor (which is what I need currently).

Does anyone know how to either get the actual TypeDescriptionProvider, or get the actual TypeDescriptor from the wrapped provider?

Thank you in advance.

Ex:

public class TestTypeDescriptionProvider : TypeDescriptionProvider
{
    private static Dictionary<Type, ICustomTypeDescriptor> _descriptors = new Dictionary<Type, ICustomTypeDescriptor>();

    ...static method to add to the cache...

    public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
    {
        if (objectType == null)
            return _descriptors[instance.GetType()];

        return _descriptors[objectType];
    }
}

...    

TypeDescriptionProvider p = TypeDescriptor.GetProvider(obj.GetType()); //p is a TypeDescriptionNode

ICustomTypeDescriptor td = p.GetTypeDescriptor(obj); // td is a DefaultTypeDescriptor
like image 643
Andrew Hanlon Avatar asked Sep 20 '11 20:09

Andrew Hanlon


1 Answers

If you look at TypeDescriptor.GetProvider implementation using a tool such as .NET Reflector, you will see that the returned type is pretty hardcoded. It always returns a TypeDescriptionNode, like you observed. Same story for GetTypeDescriptor.

Now, what you could do is use Reflection mechanisms to get the actual TypeDescriptionProvider from TypeDescriptionNode. It's pretty easy, just get the private field named Provider, this is where the TypeDescriptionNode stores the actual implementation. Of course it's not supported, but I don't think this will change in a near future, and I don't really see a better way...

like image 69
Simon Mourier Avatar answered Oct 17 '22 13:10

Simon Mourier