使用 VB.Net 获取实现特定接口的所有类类型

Spi*_*kee 3 .net vb.net reflection interface winforms

我想加载所有实现该接口的表单IFormLoadSubscriber

界面

Namespace Interfaces
    Public Interface IFormLoadSubscriber

    End Interface
End Namespace
Run Code Online (Sandbox Code Playgroud)

这时候还没有添加任何东西,订阅就够了。

形式

Namespace Forms
    Public Class MainForm
        Inherits Base.Base
        Implements IFormLoadSubscriber

    End Class
End Namespace
Run Code Online (Sandbox Code Playgroud)

Base.Base 是一种强制执行基本行为的形式。

我拥有的

Private Shared Function GetSubscribers() As List(Of Type)
    Dim type = GetType(IFormLoadSubscriber)
    Dim subscribers = AppDomain.CurrentDomain.GetAssemblies() _
                      .Where(Function(x) type.IsAssignableFrom(type)) _
                      .Select(Function(x) x.GetTypes())

    Return subscribers
End Function
Run Code Online (Sandbox Code Playgroud)

问题

上面的代码没有按预期工作,因为它返回一个很大的列表列表,包含各种类型。如果包括我的,手动查找是不可能的。无论如何,这不是我所需要的。

问题

如何更改上述代码,使其仅返回一个类(因为只有一个类实现IFormLoadSubscriber),在本例中是我的 MainForm?

小智 5

尝试将其更改为

Private Shared Function GetSubscribers() As List(Of Type)
    Dim type = GetType(IFormLoadSubscriber)
    Dim subscribers = AppDomain.CurrentDomain.GetAssemblies() _
                      .SelectMany(Function(x) x.GetTypes()) _
                      .Where(Function(x) type.IsAssignableFrom(x))

    Return subscribers
End Function
Run Code Online (Sandbox Code Playgroud)

获取实现接口的所有类型