[英]Get all class types that implement a specific interface using VB.Net
我想加載實現IFormLoadSubscriber
接口的所有窗體。
接口
Namespace Interfaces
Public Interface IFormLoadSubscriber
End Interface
End Namespace
目前,它不添加任何內容,只需訂閱即可。
形成
Namespace Forms
Public Class MainForm
Inherits Base.Base
Implements IFormLoadSubscriber
End Class
End Namespace
該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
問題
上面的代碼無法按預期方式工作,因為它返回了包含各種類型的大型列表。 如果包括我的,則不可能手動找到。 無論如何,這不是我所需要的。
問題
如何更改以上代碼,使其僅返回一個類(因為只有一個類實現IFormLoadSubscriber
),在這種情況下為MainForm?
嘗試將其更改為
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
SelectMany
將比列表列表扁平化。
Dim subscribers = AppDomain.CurrentDomain.GetAssemblies() _
.SelectMany(Function(x) x.GetTypes() _
.Where(Function(y) type.IsAssignableFrom(y)))
我也將SelectMany中的Where
子句移動了。
您的where子句也不正確, type.IsAssignableFrom(type)
始終為true。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.