简体   繁体   English

在实现特定接口的所有类型上调用通用静态方法

[英]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 . 我有一个接口IMyInterface

At run-time, I want to iterate through all the types that implement IMyInterface , and then invoke TryFindComponent<T> until it returns true . 在运行时,我想通过所有的实施何种类型的迭代IMyInterface ,然后调用TryFindComponent<T>直到它返回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> ? 我的问题是:我怎样才能通过所有实现的类型IMyInterfaceTryFindComponent<T>

Besides just the types that implement IMyInterface , you'll need instances of those types to be able to call a method on them. 除了实现IMyInterface类型之外,您还需要这些类型的实例才能在其上调用方法。

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). 然后,你可以添加其他参数TryFindComponent()需要一个(集) IMyInterface实例(S)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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