【问题标题】:Load and use type from the string class name从字符串类名加载和使用类型
【发布时间】:2014-12-20 21:46:05
【问题描述】:

我有这个方法签名

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

调用这个具有 T" 字符串表示的方法的正确方法是什么?

我的失败尝试(为清楚起见进行了简化):

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

【问题讨论】:

标签: .net vb.net reflection


【解决方案1】:

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

  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

【讨论】:

  • 在这种情况下,选择案例部分将破坏泛型的目的,因为我想使用该类而不需要知道输入的控制器类型。该类的字符串名称来自数据库。
  • 好的,我已经修改它以使用反射来创建类,以避免 SELECT CASE。我仍然认为工厂方法是比使用泛型更好的解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-11
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 2011-06-09
  • 2011-01-25
相关资源
最近更新 更多