2017-09-27 35 views
-1

我想从我的zooanimal类调用此公共子库(gutom作为字符串)到我的form1.vb。作为参考,请参阅我的代码。 我总是得到一个错误“表达式不会产生一个值”在我Textbox10.text = za.hungrys(gutom作为字符串)调用子表达式时不会产生一个值

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) 
+2

请阅读[问]并参加[旅游]。错误是准确的。 'hungrys'是一个子表示它什么都没有返回,但是你正试图分配一个结果,就像你把它写成一个函数一样......或者把这个字符串参数分配给文本框。你也应该设置'选项严格开' - '年龄'出来 – Plutonix

回答

0

更改您的SubFunction
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) 
2

如果你想获得一个值出来的SubByRef参数,而不是一个Function的返回值,那么这样的:

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

顺便说一下,这是一个可怕的,可怕的方法名称。首先,它应该从一个大写字母开始。其次,“hungrys”并没有告诉你这个方法做了什么。如果我没有上下文的阅读,我不知道它的目的是什么。

+0

这工作:)非常感谢你@ jmchilhinney。 – Blue

+0

这工作:)非常感谢你@ jmchilhinney – Blue

相关问题