Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

vb.net - expression does not produce a value when calling a sub

i want to call this public sub hungrys(gutom as string) from my zooanimal class to my form1.vb. for reference, please refer to my code. i always get an error "expression does not produce a value" in my Textbox10.text = za.hungrys(gutom as string)

Public Class ZooAnimal

Public Sub New()
hungry = isHungry()

Public Function isHungry() As Boolean
    If age > 0 Then
        hungry = True
    End If
    If age <= 0 Then
        hungry = False
    End If
    Return hungry
End Function

 Public Sub hungrys(ByRef gutom As String)
    If hungry = True Then
        gutom = "The zoo animal is hungry"
    End If
    If hungry = False Then
        gutom = "The zoo animal is not hungry "
    End If
End Sub

Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim za As New ZooAnimal
Dim gutom As String = ""

TextBox10.Text = za.hungrys(gutom)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are trying to get a value out of a Sub with a ByRef parameter rather than the return value of a Function then this:

TextBox10.Text = za.hungrys(gutom)

would need to be this:

za.hungrys(gutom)
TextBox10.Text = gutom

The first line calls the Sub and assigns a new value to the variable and the second line displays the variable's value in the TextBox.

Unless it's as a learning exercise though, there's no good reason to use a ByRef parameter there. You'd normally write that method like this:

Public Function hungrys() As String
    Dim gutom As String

    If hungry Then
        gutom = "The zoo animal is hungry"
    Else
        gutom = "The zoo animal is not hungry "
    End If

    Return gutom
End Sub

and then call it like this:

Dim gutom As String = za.hungrys()

TextBox10.Text = gutom

or just:

TextBox10.Text = za.hungrys()

Notice that that method uses an If...Else rather than two separate If blocks.

By the way, that is a terrible, terrible name for a method. Firstly, it should start with an upper-case letter. Secondly, "hungrys" doesn't tell you what the method does. If I read that with no context, I'd have little idea what it's purpose was.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...