简体   繁体   中英

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM