簡體   English   中英

從C#中的通用接口查找實現的類型

[英]Find implemented types from Generic interface in c#

public class AccountCreatedEvent : EventBase{}   

 public class AccountHandler : IEventHandler<AccountCreatedEvent>
    {
        public void Handle(AccountCreatedEvent event)
        {
        }
    }

這是一個處理程序類,我想使用c#代碼獲取此類。 我想從IEventHandler類型獲取已實現類的列表。

public class Account
{
    public void OnAccountCreated(EventBase accountCreatedEvent)
    {            
        var handler = typeof(IEventHandler<>);            
        var events = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(s => s.GetTypes())
            .Where(p => handler .IsAssignableFrom(p) && handler.IsGenericType);

    }
}

但是var events又回來了

 {Name = "IEventHandler`1" FullName = "Project1.IEventHandler`1"}

如Praveen所建議,但是使用了如何處理通用接口

Type interfaceType = typeof(IEventHandler<>);
Assembly mscorlib = typeof(System.Int32).Assembly;
Assembly system = typeof(System.Uri).Assembly;
Assembly systemcore = typeof(System.Linq.Enumerable).Assembly;

var events = AppDomain.CurrentDomain.GetAssemblies()
    // We skip three common assemblies of Microsoft
    .Where(x => x != mscorlib && x != system && x != systemcore).ToArray();
    .SelectMany(s => s.GetTypes())
    .Where(p => p.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType)).ToArray();

請注意,為了稍微加快速度,我跳過了Microsoft的三個常見程序集。 跳過所有MS程序集要稍微復雜一點(可以通過PublicKeyToken來完成,但是我認為這不是一個非常好的主意... PublicKeyToken是64位的,並且不能真正保證是唯一的...並且檢索程序集的完整PublicKey可能很麻煩)

以下代碼將獲取實現IEventHandler接口的所有類型的列表

var events = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(s => s.GetTypes())
            .Where(p => p.GetInterfaces().Any(i => i.Name == handler.Name && i.Namespace == handler.Namespace));

我們基本上是在檢查類實現的所有接口是否都與處理程序接口名稱匹配。 您可以限制檢查其他參數(例如名稱空間)的限制,以防您要跨程序集搜索。

暫無
暫無

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

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