簡體   English   中英

在實現特定接口的所有類型上調用通用靜態方法

[英]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  
}

我的問題是:我怎樣才能通過所有實現的類型IMyInterfaceTryFindComponent<T>

除了實現IMyInterface類型之外,您還需要這些類型的實例才能在其上調用方法。

如果實現具有無參數構造函數,則可以使用

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

創建每個匹配類型的實例。

然后,你可以添加其他參數TryFindComponent()需要一個(集) IMyInterface實例(S)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM