2013-09-10 32 views
0

請參閱下面的代碼:反思 - 從一個字符串值,創建數據類型

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 

我懷疑有與反思這樣做的一個簡單的方法(更少的代碼)?

+0

使用[泛型](http://msdn.microsoft.com/en-us/library/4a1b71ta.aspx)而不是反射。 –

+0

並使用'Enum'而不是字符串,並且'VB.NET'是否有'default'關鍵字? – ja72

+1

@ ja72:VB.NET擁有全能的'Nothing'。 :) – Neolisk

回答

3

您可以Activator.CreateInstance一起使用Type.GetType

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")

+0

謝謝+1。你知道是否可以用參考對象來做到這一點,例如getObject(「Person」)或getObject(「string」)? – w0051977

+0

@ w0051977:'GetType'也適用於參考類型。只要確保你的類是完全限定的,即'YourAppName.Person'和'System.String'。 – Neolisk

0

真正的問題是你想要解決什麼問題?激活器將工作。正在嘗試創建一個工廠或IOC容器。你能否提供更多細節?你也可以創建一個字典,關鍵是字符串類型,然後項目存儲用於實際創建類型的委託。

相關問題