2017-09-27 73 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

相關問題