【问题标题】:expression does not produce a value when calling a sub调用子时表达式不产生值
【发布时间】:2017-09-27 00:21:39
【问题描述】:

我想将我的 zooanimal 类中的这个公共子饥饿(gutom 作为字符串)称为我的 form1.vb。供参考,请参阅我的代码。 我的 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)

【问题讨论】:

  • 请阅读How to Ask 并使用tour。错误是准确的。 hungrys 是一个 sub ,这意味着它什么也不返回,但是您正试图分配一个结果,就好像您将它编写为一个函数一样......或者将该字符串参数分配给文本框。您还应该设置Option Strict On - age 不知从何而来

标签: vb.net oop methods


【解决方案1】:

如果您尝试使用 ByRef 参数而不是 Function 的返回值从 Sub 中获取值,那么:

TextBox10.Text = za.hungrys(gutom)

应该是这样的:

za.hungrys(gutom)
TextBox10.Text = gutom

第一行调用Sub 并为变量分配一个新值,第二行在TextBox 中显示变量的值。

除非作为学习练习,否则没有充分的理由在此处使用 ByRef 参数。您通常会这样编写该方法:

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 块。

顺便说一句,这是一个可怕的、可怕的方法名称。首先,它应该以大写字母开头。其次,“饥饿”并没有告诉您该方法的作用。如果我在没有上下文的情况下阅读它,我几乎不知道它的目的是什么。

【讨论】:

    【解决方案2】:

    将您的 Sub 更改为 Function
    Sub返回值的过程。
    Function 会返回值。
    就是这么简单。

    另外,声明参数gutom As Boolean 的数据类型,因为它存储的值可能是True or False

    不要使用多余的If.. 改用If-Else

    Public Function hungrys(ByVal gutom As Boolean) As String
      If hungry = True Then
          gutom = "The zoo animal is hungry"
      Else
          gutom = "The zoo animal is not hungry "
      End If
      Return gutom
    End Function
    

    称呼它

    TextBox10.Text = za.hungrys(True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-11
      • 1970-01-01
      • 2012-08-13
      • 2020-06-23
      • 2012-05-11
      • 2015-10-10
      • 1970-01-01
      相关资源
      最近更新 更多