在vb.net foreach

时间:2017-09-05 11:23:50

标签: vb.net

我是vb.net的新手,想在foreach中返回两个值,你能帮助我吗?

For Each item In Function ()
         test1 = I would like to get the result1 here
         test2 = I would like to get the result2 here
     Next

Private Function Function () As String
     Dim result1  As String
     Dim result2 As String

     result1 = "Test"
     result2 = "Test2"

     Return result1

End Function

2 个答案:

答案 0 :(得分:1)

有大量的物品可以满足这种需要..

  • Tuple似乎正是您所寻找的:

    Return New Tuple(Of String, Of String)(result1 , result2)
    

但其他解决方案,如List,Array,Custom Class,KeyValuePair,ValueTuple

答案 1 :(得分:1)

取决于您将如何使用您的功能。

您可以返回名为ValueTuple Tuples as method return values

Private Function Get() As (One As String, Two As String)
    Return (One:= "one", Two:= "two")
End Function

Dim values = Get()
value.One ' one
value.Two 'two

您可以创建并返回自己类的实例

Public Class Values
    Public Property One As String
    Public Property Two As String
End Class

Private Function Get() As Values
    Return New Values With { .One = "one", .Two = "two" }
End Function

Dim values = Get()
value.One ' one
value.Two 'two   

从性能的角度来看,没有太大差异,因此决策更多地基于可读性和可维护性。

如果您在多个地方使用相同的返回类型,或者您希望将其传递给其他函数,则类将是首选方法。