首页 > 解决方案 > vb.net 从函数调用特定字符串

问题描述

我有这个代码:

Function f1(ByVal x As String, ByVal o As String)
    x = "me"
    o = "you"
    Return {x.ToString, o.ToString}
End Function

Function f2()
    Dim a As String = "i love" & f1(Nothing, ToString)
End Function

我正在尝试从函数 f1() 中获取字符串 (o) 以在 f2() 中使用它但不工作。

标签: vb.netvisual-studio

解决方案


您应该打开 Option Strict On,因为该示例存在很多错误。

Function f1(ByVal x As String, ByVal o As String) As String() ' x and o are useless parameters
    x = "me"
    o = "you"
    Return {x.ToString, o.ToString} ' Returns an array of string
End Function

Function f2() ' Method not returning anything
    Dim a As String = "i love" & f1(Nothing, Me.ToString()).ToString() ' Can't really concatenate an array to a string. Also, parameter Me.ToString() doesn't make much sense
End Function

我建议你从像这样更简单的东西开始。

Function f1() As String
    Dim o As String = "you"
    Return o
End Function

Function f2() As String
    Dim a As String = "I love " & f1()
    Return a
End Function

然后添加一个参数来选择不同的返回值

Function f1(ByVal mustReturnX As Boolean) As String
    Dim x As String = "me"
    Dim o As String = "you"

    If mustReturnX Then
        Return x
    End If

    Return o
End Function

Function f2() As String
    Dim a As String = "i love " & f1(True)
    Return a
End Function

没有明确的要求,我们无能为力。


推荐阅读