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

时间:2018-02-19 12:34:21

标签: c# reflection

这是我的扩展方法:

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

我有一个界面IMyInterface

在运行时,我想迭代实现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  
}

我的问题是:如何将实施IMyInterface的所有类型传递给TryFindComponent<T>

1 个答案:

答案 0 :(得分:0)

除了实现IMyInterface types 之外,您还需要 这些类型的实例才能调用它们的方法。

如果实现具有无参数构造函数,则可以使用

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

创建每个匹配类型的实例。

然后,您可以向TryFindComponent()添加另一个参数,该参数包含IMyInterface个实例的集合。