2017-05-03 58 views
0

爲什麼不將對象的數據類型傳遞給函數?你如何解決它?如何使用GetType並將其傳遞給函數

Dim MyObj as new CustomObj 
Dim t As Type = MyObj.GetType 
Call My_Fuction(Of t) 

我節省序列化對象到文件,然後打開它們以後,然後將代碼需要基於對象的數據類型,找到用戶界面,因此它可以從對象填充UI

Private Function My_Fuction(Of t As Base_Object)() As UserControl 
Dim UI_Type As Type = GetType(UI_Common_Panel(Of t)) 
For Each Object_type As Type In Project_Solution.GetTypes()  
For Each Itype As Type In Object_type.GetInterfaces() 
     If Itype Is UI_Type Then Return DirectCast(Activator.CreateInstance(Object_type), UI_Common_Panel(Of t))  
Next 
Next 
Return Nothing 
End Function 
+1

爲什麼你標記VB.NET代碼爲C#? – itsme86

+0

我已經標記了兩個,因爲我會接受任何一種語言的答案 –

+2

我認爲你很困惑如何通用約束工作 – Plutonix

回答

0

由於您的問題中包含所有自定義類,因此很難給出正確答案。如果你正在試圖解決的問題是創建一個基於新的控制對象的Type,這裏是一個辦法做到這一點使用內置控件:

Function GetControl(o As Object) As Control 
    If o.GetType Is GetType(Boolean) Then 
    Return New CheckBox With {.Checked = DirectCast(o, Boolean)} 
    ElseIf o.GetType Is GetType(Date) Then 
    Return New DateTimePicker With {.Value = DirectCast(o, Date)} 
    ElseIf o.GetType Is GetType(String) Then 
    Return New TextBox With {.Text = DirectCast(o, String)} 
    Else 
    Return New TextBox With {.Text = o.ToString} 
    End If 
End Function 

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    Dim c As Control = GetControl("Hello, world!") 
    Me.Controls.Add(c) 
    c.Visible = True 

    Dim c2 As Control = GetControl(#05/04/2017#) 
    Me.Controls.Add(c2) 
    c2.Visible = True 
    c2.Top = 100 
End Sub 
相關問題