2016-04-03 50 views
1

檢查類型參數是否爲某類型X(或源自某個類型X)的正確方法是什麼?例如。檢查通用參數類型是否來自某個類別X

Function MyFunc(Of T As BaseClass)() As T 
    If TypeOf T Is GetType(ChildClass1) Then 
    'Do something specific to ChildClass1 
    End If 

    'Do things common to all BaseClass objects 
End Function 

上述代碼不編譯,有或沒有TypeOf

+0

嘗試'如果的GetType(T)是的GetType(ChildClass1)Then' –

+0

@ZoharPeled:顯然我錯過了什麼這麼簡單。感謝您的意見。如果您發佈,我會接受該答案。 – dotNET

回答

2

TypeOf T替換爲GetType(T)
您的代碼應該是這樣的:

Function MyFunc(Of T As BaseClass)() As T 
    If GetType(T) Is GetType(ChildClass1) Then 
    'Do something specific to ChildClass1 
    End If 

    'Do things common to all BaseClass objects 
End Function 
相關問題