从字符串类名称加载和使用类型

时间:2014-12-20 21:46:05

标签: .net vb.net reflection

我有这个方法签名

Public Function As CreateWorkItem(Of T)() As WorkItem

使用T"?

的字符串表示来调用此方法的正确方法是什么

我的失败尝试(为简洁而简化):

Dim controllerType As Type = Type.GetType("AccountingController")
CreateWorkItem(Of controllerType)()

1 个答案:

答案 0 :(得分:0)

使用共享工厂方法而不是泛型:

  Public Class WorkItem
    Property MyProperty As String
    Public Shared Function CreateWorkItem(TypeName As String) As WorkItem
      Static sstrNamespace As String = ""
      If sstrNamespace = "" Then
        sstrNamespace = GetType(WorkItem).FullName
        sstrNamespace = sstrNamespace.Substring(0, sstrNamespace.Length - 8) '"WorkItem"=8 characters
      End If
      Dim strFullName As String = sstrNamespace & TypeName 'assume qualified namespace of subclasses are the same as the WorkItem base class
      Dim wi As WorkItem = Nothing
      Try
        wi = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(strFullName)
      Catch ex As Exception
      End Try
      Return wi
    End Function
  End Class

  Public Class AccountingController
    Inherits WorkItem
    Sub New()
      Me.MyProperty = "AccountingController"
    End Sub
  End Class

  Public Class SomethingElse
    Inherits WorkItem
    Sub New()
      Me.MyProperty = "SomethingElse"
    End Sub
  End Class

  Sub Main()
    Dim wi As WorkItem = WorkItem.CreateWorkItem("AccountingController")
    MsgBox(wi.MyProperty)
    Dim wi2 As WorkItem = WorkItem.CreateWorkItem("SomethingElse")
    MsgBox(wi2.MyProperty)
  End Sub