![](/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.