lundi 19 octobre 2015

Why would a closed generic type not be returned by Assembly.GetType()?

I have created a generic JavaScriptConverter derivation for a custom generic class (TabularList<>) which I have dubbed ITabularConverter<>. The ITabularConverter uses reflection to retrieve all of the closed types derived from the TabularList<> generic type definition. That code looks like this:

public override IEnumerable<Type> SupportedTypes
{
    get
    {
        var type = typeof (TabularList<>);
        var itabulars = Assembly.GetAssembly(type).GetTypes()
            .Where(t => t.IsGenericType 
                && t.GetGenericTypeDefinition() == type);
        return itabulars;
    }
}

The problem is, even though there is at least one closed type of TabularList<> in existence by the time this code executes, only the open generic type definition is returned by the above code. The same is true when I expand the search to all currently loaded assemblies.

What's even stranger is that if I examine the call stack, I can see where the JavaScriptSerializer.Serialize method is being invoked and use the immediate window to examine the object being serialized and prove that a closed version of the generic definition exists. Yet, when I execute the following code in the Immediate Window, the result is false:

Assembly.GetAssembly(obj.TabularListProp.GetType())
    .GetTypes()
    .Contains(obj.TabularListProp.GetType());

So I retrieve the assembly in which the closed generic is defined and then look for the closed generic type among the types defined by that assembly, and the closed type is not found. How does that make any sense?





Aucun commentaire:

Enregistrer un commentaire