![](/img/trans.png)
[英]Find all types implementing a certain generic interface with specific T type
[英]Calling generic static method on all types implementing a specific interface
这是我的扩展方法:
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>
除了实现IMyInterface
的类型之外,您还需要这些类型的实例才能在其上调用方法。
如果实现具有无参数构造函数,则可以使用
var instance = (IMyInterface)Activator.CreateInstance(myIMyInterfaceType);
创建每个匹配类型的实例。
然后,你可以添加其他参数TryFindComponent()
需要一个(集) IMyInterface
实例(S)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.