具有多个输出的VB函数 - 分配结果

时间:2013-05-08 09:19:42

标签: vb.net function variable-assignment mass-assignment

我知道在VB中没有直接的方法来进行多项功能分配,但是我的解决方案是 - 它是好的,你会怎样做得更好?

我需要什么(我将如何在python中进行,只是一个例子)

def foo(a)    ' function with multiple output
    return int(a), int(a)+1

FloorOfA, CeilOfA = foo(a) 'now the assignment of results

我是如何在VB中完成的:

Public Function foo(ByVal nA As Integer) As Integer() ' function with multiple output
    Return {CInt(nA),CInt(nA)+1}
End Function

Dim Output As Integer() = foo(nA) 'now the assignment of results
Dim FloorOfA As Integer = Output(0)
Dim CeilOfA As Integer = Output(1)

3 个答案:

答案 0 :(得分:8)

您的解决方案有效,这是一种返回多个结果的优雅方式,但您也可以尝试使用此

Public Sub foo2(ByVal nA As Integer, ByRef a1 As Integer, ByRef a2 As Integer) 
    a1 = Convert.ToInt32(nA)
    a2 = Convert.ToInt32(nA) +1
End Sub

并致电

foo2(nA, CeilOfA, FloorOfA)    

如果你要返回很多结果,那么考虑一个可以返回所有需要的值的类是合乎逻辑的(特别是如果这些值具有不同的数据类型)

Public Class CalcParams
   Public p1 As Integer
   Public p2 As String
   Public p3 As DateTime
   Public p4 As List(Of String)
End Class

Public Function foo2(ByVal nA As Integer) As CalcParams
    Dim cp = new CalcParams()
    cp.p1 = Convert.ToInt32(nA)
    .......
    Return cp
End Function

答案 1 :(得分:3)

也许您可以使用Tuple

Public Function foo(ByVal nA As Integer) As Tuple(Of Integer,Integer) ' function with multiple output
    Return Tuple.Create(CInt(nA),CInt(nA)+1)
End Function

Dim FloorOfA, CeilOfA As Integer
With foo(nA) 'now the assignment of results
   FloorOfA =.item1
   CeilOfA = .item2
End With

编辑:由Tuple.Create替换新元组(感谢@ mbomb007)

答案 2 :(得分:2)

您正在使用的方法很好,顺便说一句,您可以将所需的变量作为reference传递到subroutine,以使code更清洁。< / p>

Dim FloorOfA As Integer
Dim CeilOfA As Integer

Call foo(10.5, FloorOfA, CeilOfA)

Public Sub foo(ByVal xVal As Integer, ByRef x As Integer, ByRef y As Integer)
    x = CInt(xVal)
    y = CInt(xVal) + 1
End Sub