我有这个方法签名
Public Function As CreateWorkItem(Of T)() As WorkItem
使用T"?
的字符串表示来调用此方法的正确方法是什么我的失败尝试(为简洁而简化):
Dim controllerType As Type = Type.GetType("AccountingController")
CreateWorkItem(Of controllerType)()
答案 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