如何从一个函数中的不同函数访问返回的变量?

How do I access a returned variable from a different function within a function?

我有一个函数“A”,它从 SSRS 中的文本框中检索整数值:

Dim currasm As Integer = Nothing
Function GetAsmCurrent(ByVal currasm As Integer) As Integer
    Return currasm
End Function

...还有第二个函数“B”,我想在其中使用从函数“A”返回的值。

Dim lastsn As String = Nothing
Function GetSN(ByVal currentsn As String) As String
    Dim currasm1 As Integer = Nothing
    ' <------ Here is where I thought I could call the function ------>
    currasm1 = GetAsmCurrent(currasm)
    ' <--------------------------------------------------------------->
    If Not currasm1 = Nothing And currentsn = Nothing Then "NO SN"
    ElseIf Not currentsn = Nothing Then
        lastsn = currentsn
    End If
    Return lastsn
End Function

它总是拉入 0,而不是 1、2 等,具体取决于报告页面上文本框中的程序集编号。

Private currasm As Integer 
Function GetAsmCurrent(ByVal currasm As Integer) As Integer
    Return currasm
End Function

此函数将return 传递给它的值,而不是class 级别变量。代码将始终在最近的范围内寻找变量。 return 传递的内容有点傻。同样,正如我在评论中所述,值类型具有默认值,在本例中为 0 并且不能设置为 Nothing 除非可为空。对于class级变量,习惯上使用Private代替Dim

Private lastsn As String = Nothing

Function GetSN(ByVal currentsn As String) As String
    Dim currasm1 As Integer 
    currasm1 = GetAsmCurrent(currasm)
    If Not currasm1 = 0 And currentsn = Nothing Then
        currentsn = "NO SN" 
    ElseIf Not currentsn = Nothing Then
            lastsn = currentsn
    End If
    Return lastsn
End Function

在这个函数中GetAsmCurrent(currasm)将传递class级别变量的值和return相同的值。假设 2 个函数在同一个 class 中,只说 currasm1 = currasm 可能更容易。如上所述,currasm1 不能是 Nothing.

这不会编译 "NO SN"。那可能意味着什么?您是否打算将该字符串分配给某个变量?我假设您打算将其分配给 currentsn.

如果您在同一个 class 中调用此函数,它可以是一个 Sub。 class 中的任何方法都可以访问 class 级变量。