如何设置泛型返回类型

时间:2014-11-14 18:35:33

标签: vb.net

我从单元格读取值并且返回没有修复。我没有为每个返回类型编写许多函数,而是尝试编写一个具有泛型返回类型的函数,但我坚持这样:

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

无论我在单元格中找到什么类型,我都想将值转换为我在函数中设置的返回类型。但我所有的尝试都是徒劳的。如果有人能帮助我完成这项工作,那就太好了。

2 个答案:

答案 0 :(得分:1)

自从我接触VB.Net以来已经有一段时间了,但你应该能够做到这一点:

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

答案 1 :(得分:0)

我会解决几件事。

使用更具描述性的Generic Type参数,只声明Generic的类型并返回它。

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