声明实现接口的类的新实例

时间:2014-07-31 16:23:28

标签: vb.net

Private Sub LoadJobs()
    Dim thisContract As iOutboundContract
    Dim results = From type In System.Reflection.Assembly.GetExecutingAssembly.GetTypes()
                  Where GetType(iOutboundContract).IsAssignableFrom(type)
                  Select type
    For Each outboundContract In results
        If outboundContract.Name <> "iOutboundContract" Then
            thisContract = New outboundContract ' <- This line isn't real.  This is what I want to do.
        End If
    Next
End Sub

在上面的过程中,我能够为每个枚举一个查找实现特定接口的所有类。现在我想为实现契约的每个类声明一个变量。出于某种原因,我没有在谷歌搜索中添加适当的单词。

1 个答案:

答案 0 :(得分:3)

.net reflection create instance of type会为您提供大量搜索结果,例如Activator.CreateInstance

用法是:

Sub LoadJobs()
    Dim contracts As New List(Of iOutboundContract)()

    Dim results = From type In System.Reflection.Assembly.GetExecutingAssembly.GetTypes()
                  Where GetType(iOutboundContract).IsAssignableFrom(type) AndAlso Not type.IsAbstract AndAlso Not type.IsInterface
                  Select type

    For Each outboundContract In results
        contracts.Add(DirectCast(Activator.CreateInstance(outboundContract), iOutboundContract))
    Next
End Sub

从结果中排除抽象类和接口。否则会出错。还要确保该类具有默认构造函数(否则您将不得不使用Activator.CreateInstance方法的重载方法。)

略微注意;在.NET接口中通常以大写I(i)开头。我建议你也使用这个约定。我将您的iOutboundContract(界面)重命名为IOutboundContract