调用子程序时表达式不产生值 [英] expression does not produce a value when calling a sub

查看:241
本文介绍了调用子程序时表达式不产生值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的动物类到我的form1.vb将此公共子级饥饿(以字符串形式表示).供参考,请参阅我的代码. 我总是在Textbox10.text = za.hungrys(以字符串形式表示)中收到错误消息表达式不能产生值"

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)

推荐答案

如果尝试使用ByRef参数从Sub中获取值,而不是Function的返回值,则此操作:

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)

需要是这样的:

za.hungrys(gutom)
TextBox10.Text = gutom

第一行调用Sub并将新值分配给变量,第二行在TextBox中显示变量的值.

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.

但是,除非这是一项学习练习,否则没有充分的理由在那里使用ByRef参数.通常,您可以这样编写该方法:

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

然后这样称呼它:

Dim gutom As String = za.hungrys()

TextBox10.Text = gutom

或者只是:

TextBox10.Text = za.hungrys()

请注意,该方法使用If...Else而不是两个单独的If块.

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.

这篇关于调用子程序时表达式不产生值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆