0

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>?

M.Y. Babt
  • 2,733
  • 7
  • 27
  • 49
  • Possible duplicate of [How do I use reflection to call a generic method?](https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method) – thehennyy Feb 19 '18 at 12:35

1 Answers1

0

Besides just the types that implement IMyInterface, you'll need instances of those types to be able to call a method on them.

If the implementations have parameterless constructors you could use

var instance = (IMyInterface)Activator.CreateInstance(myIMyInterfaceType);

to create an instance of each matching type.

Then you could add another parameter to TryFindComponent() that takes a (collection of) IMyInterface instance(s).

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72