lundi 19 février 2018

Calling generic static method on all types implementing a specific interface

Here is my extension method:

public static class ComponentExtensions
{
    public static bool TryFindComponent<T>(this Component parentComponent, out T foundComponent)
    {
        foundComponent = parentComponent.GetComponent<T>();
        return foundComponent != null;
    }
}

I have an interface IMyInterface.

At run-time, I want to iterate through all the types that implement IMyInterface, and then invoke TryFindComponent<T> until it returns true.

IEnumerable<Type> grabbableTypes =
                AppDomain.CurrentDomain
                         .GetAssemblies()
                         .SelectMany(assembly => assembly.GetTypes())
                         .Where(type => typeof(IMyInterface).IsAssignableFrom(type));

foreach (var type in grabbableTypes)
{
    // Call TryFindComponent<T>: 
    // if true, do something to the object assigned to the "out" variable, and then return immediately; 
    // otherwise, continue  
}

My question is: How can I pass all the types that implement IMyInterface to TryFindComponent<T>?





Aucun commentaire:

Enregistrer un commentaire