2014-11-14 91 views
0

我從單元中讀取值,並且返回值未修復。而不是寫很多功能對每個返回類型的我試着寫一個函數與通用返回類型,但我還是堅持了這一點:如何設置通用返回類型

Public Function GetValueFromCells(Of t)(ByVal CellName As String) As t 
    Return CType(_xlWorksheet.Range(CellName).Value2) 
End Function 

無論我將在小區找什麼類型的,我要的值轉換到我在函數中設置的返回類型。但我所有的嘗試都是徒勞的。如果有人能幫助我完成這個任務,那將是非常棒的。

回答

1

它已經一段時間,因爲我感動VB.Net,但你應該能夠做到這一點:

Public Function GetValueFromCells(Of t)(ByVal CellName As String) As t 
    Return CType(_xlWorksheet.Range(CellName).Value2, t) 
End Function 
0

我將解決幾件事情。

使用更多的描述性泛型類型參數,只聲明通用類型並返回它。

Public Function GetValueFromCells(Of TCellValue)(ByVal cellName As String) As TCellValue 
    Dim specificValue As TCellValue = Nothing 
    specificValue = DirectCast(_xlWorksheet.Range(cellName).Value2, TCellValue) 
    Return specificValue 
End Function