mercredi 9 novembre 2016

Reflection Get List from List

I have a peculiar situation where in one of reflectors I can get different types of containers that I need to reinflate (like make clones of). This started happening when new type of container was introduced (ObservableCollection<T>)

Within cloning mechanism what I have found was this:

if (property.PropertyType.FullName.Contains(ReflectorResources.ListName) || property.PropertyType.FullName.Contains("ConcurrentBag"))
{
    var listElementType = property.PropertyType.GenericTypeArguments[0];
    var newList = (property.PropertyType.FullName.Contains(ReflectorResources.IncidentListName))
         ? Activator.CreateInstance(typeof(Definitions.Session.Products.Motor.IncidentList<>).MakeGenericType(listElementType))
         : property.PropertyType.FullName.Contains("ConcurrentBag") ? Activator.CreateInstance(typeof(ConcurrentBag<>).MakeGenericType(listElementType)) : Activator.CreateInstance(typeof(List<>).MakeGenericType(listElementType));    
    var oneItem = Activator.CreateInstance(listElementType);
}

So I tried to rewrite it like:

if (new[] { ".Collections." }.Any(o => property.PropertyType.FullName.Contains(o)))
{
    var listElementType = property.PropertyType.GenericTypeArguments[0];
    var listType = property.PropertyType;
    var constructedListType = listType.MakeGenericType(listElementType);
    var newList = Activator.CreateInstance(constructedListType);
    var oneItem = Activator.CreateInstance(listElementType);
}

however it blows up on the line: var constructedListType = listType.MakeGenericType(listElementType); with error

System.InvalidOperationException : Method may only be called on a Type for which Type.IsGenericParameter is true.

My guess is that I need to extract List<> type from List<Something>...

How do I get container type from generic container type?





Aucun commentaire:

Enregistrer un commentaire