How to find all the objects that implement ICollection?

0

Given this property:

Public Overridable Property Collecions As ICollection(Of String)

Which we could instantiate like this:

variable.Collecions = New List(Of String)

Or like this:

variable.Collecions = New LinkedList(Of String)

The following question arises: Is not there an easy way to find all types that implement ICollection , and therefore can be instantiated? I expected to find them through the object examiner, but I have not seen how. My searches on google have not thrown too much light either. Thanks in advance.

    
asked by Sergio Garcia 12.07.2017 в 19:48
source

1 answer

0

It is necessary to look for all the types that implement the interface with the method IsAssignableFrom that verifies if the instance can be assigned to System.Type passed by parameter:

public ICollection<T> GetAllICollectionTTypes<T>()
{
 var collectionType = typeof(ICollection<T>);
 var collections = typeof(ICollection<T>);
            var collections = Assembly.GetExecutingAssembly().GetTypes()
                .Where(x => collectionType.IsAssignableFrom(x))
                 .Select(x=> Activator.CreateInstance<ICollection<T>>(x))
                .ToList();

return collections
}

The Activator.CreateInstance<ICollection<T>> method creates a new instance of the found type.

Usage:

ICollection<string> instanciasQueImplementanICollectionString = GetAllICollectionTTypes<String>();
    
answered by 12.07.2017 в 20:18