反射 - 从字符串文字值创建数据类型

时间:2013-09-10 22:10:15

标签: vb.net

请参阅以下代码:

Public Function Test()
    Dim o As Object = getVariable("Integer")
    If TypeOf o Is Integer Then
        'Do some processing on the integer
    ElseIf TypeOf o Is Decimal Then
        'Do some processing on the integer
    End If
End Function

Public Function getVariable(ByVal strDataType As String)
    If strDataType = "Integer" Then
        Return New Integer
    ElseIf strDataType = "Decimal" Then
        Return New Decimal
    ElseIf strDataType = "Double" Then
        Return New Double
    End If
End Function

我怀疑使用Reflection有一种更简单的方法(更少的代码行)?

2 个答案:

答案 0 :(得分:3)

您可以将Type.GetTypeActivator.CreateInstance一起使用:

Public Function getVariable(ByVal strDataType As String)
  Return Activator.CreateInstance(Type.GetType(strDataType))
End Function

对于strDataType,您需要分别使用System.Int32System.DecimalSystem.Double。如果您想将其保留为Integer等,则需要合并字符串翻译,例如,使用Dictionary(Of String, String),其中包含("Integer", "System.Int32")等条目。

答案 1 :(得分:0)

真正的问题是你试图解决的问题是什么? Activator会起作用。正在尝试创建工厂或IOC容器。你能提供更多细节吗?你也可以创建一个字典,键是字符串类型,然后item存储用于实际创建类型的委托。

相关问题