[英]Public Function vs Public Sub
我編寫了一個簡單的程序來計算線性序列中的前5個數字。 該程序最初是順序的,涉及Main()中的一個子項來執行計算。 但是,作為一個相對初級的編碼人員,我試圖加深對面向對象編程的理解,因此,作為一個挑戰,我決定相應地重新編寫程序。 從下面的代碼中您將看到,我遇到了一個難題,我希望其中一些人可以幫助我。
通過使用公共子程序,我可以通過在Main()中創建該類的新實例並調用GetSequence來執行所需的任務……沒問題。 但是,我不喜歡在類中使用Console.Write行的想法。 如果我錯了,請糾正我,但是由於它刪除了動態功能,這不會否定創建類的真正目的嗎?
因此,作為替代,我嘗試在公共函數中執行相同的計算,但是不幸的是,在for循環中無法識別返回值。 我敢肯定有辦法解決這個問題……我已經錯過了顯而易見的東西,但我只是看不到它。
與往常一樣,對此的任何幫助都將受到贊賞。
Public Class Sequence
Public Property a As Integer
Public Property b As Integer
'Using Public Sub does the job, but it means using a
'Console.Write within the Sequence class, which I'm
'not too happy about.
Public Sub GetSequence()
For n = 1 To 5
Console.Write("{0}, ", a * n + b)
Next
End Sub
'I'd prefer to use a Public Function, but how do I
'return the value of the function through each iteration
'of the 'for' loop?
Public Function GetSequence(ByVal a As Integer, ByVal b As Integer)
For n = 0 To 5
Return a * n + b
Next
End Function
Public Sub New(ByVal a As Integer, ByVal b As Integer)
Me.a = a
Me.b = b
End Sub
End Class
您可能希望使用yield語句-查看以下鏈接:
給出的示例代碼如下:
Sub Main()
For Each number In Power(2, 8)
Console.Write(number & " ")
Next
' Output: 2 4 8 16 32 64 128 256
Console.ReadKey()
End Sub
Private Iterator Function Power(
ByVal base As Integer, ByVal highExponent As Integer) _
As System.Collections.Generic.IEnumerable(Of Integer)
Dim result = 1
For counter = 1 To highExponent
result = result * base
Yield result
Next
End Function
請注意,For Each循環正在調用該函數,該函數定義為Iterator,這使得有可能將每個生成的結果的值返回給For Each。
對於這個小示例,您可以創建一個字符串並重復附加到該字符串(還要確保聲明該函數的返回類型–在整個項目范圍內啟用Option Strict
):
Public Function GetSequence(a As Integer, b As Integer) As String
Dim result As String = ""
For n = 0 To 5
result &= (a * n + b) & ", "
Next
Return result
End Function
LINQ更好,但也許比您現在想了解的要先進。
Public Function GetSequence(a As Integer, b As Integer) As String
Return String.Join(
", ",
From n In Enumerable.Range(0, 6) Select (a * n + b).ToString()
)
End Function
因此,您希望“序列”成為一個實體,並且希望能夠從外部枚舉該實體的值。
慣用的方式是實現IEnumerable
接口:
Public Class Sequence
Implements IEnumerable(Of Integer)
Public ReadOnly Property a As Integer
Public ReadOnly Property b As Integer
Public Sub New(ByVal a As Integer, ByVal b As Integer)
Me.a = a
Me.b = b
End Sub
Public Iterator Function GetEnumerator() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator
For n = 0 To 5
Yield a * n + b
Next
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return Me.GetEnumerator()
End Function
End Class
Dim s As New Sequence(1, 3)
For Each i In s
Console.WriteLine(i)
Next
Console.ReadLine()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.