2009-05-17 101 views
9

可能重複:
Yield In VB.NET我可以在VB.NET中實現IEnumerable函數的yield return嗎?

在C#中,編寫返回IEnumerble<>一個功能時,您可以使用yield return返回枚舉的單個項目和yield break;表示沒有剩餘項目。什麼是做同樣的事情的VB.NET語法?

NerdDinner代碼的示例:

public IEnumerable<RuleViolation> GetRuleViolations() { 

    if (String.IsNullOrEmpty(Title)) 
     yield return new RuleViolation("Title required","Title"); 

    if (String.IsNullOrEmpty(Description)) 
     yield return new RuleViolation("Description required","Description"); 

    if (String.IsNullOrEmpty(HostedBy)) 
     yield return new RuleViolation("HostedBy required", "HostedBy"); 

    if (String.IsNullOrEmpty(Address)) 
     yield return new RuleViolation("Address required", "Address"); 

    if (String.IsNullOrEmpty(Country)) 
     yield return new RuleViolation("Country required", "Country"); 

    if (String.IsNullOrEmpty(ContactPhone)) 
     yield return new RuleViolation("Phone# required", "ContactPhone"); 

    if (!PhoneValidator.IsValidNumber(ContactPhone, Country)) 
     yield return new RuleViolation("Phone# does not match country", "ContactPhone"); 

    yield break; 
} 

convert C# to VB.NET tool給出了一個 「YieldStatement是不受支持的」 錯誤。

+0

請注意,屈服不會返回,至少在大多數人意味着返回的意義上(儘管它是在引擎蓋下實現的)。另外,你不需要在那裏獲得收益。此外,您可能想考慮將該代碼轉換爲產生枚舉的RuleViolation對象,以產生Func 委託的枚舉。 – yfeldblum 2009-05-17 22:02:46

+0

使用yield讓我想起那個調用代碼中的管道可以通過*之前*啓動遍歷所有可返回的功能完成運行的功能。很酷! – 2009-05-17 22:15:09

回答

0

在VB.NET沒有屈服回報:( 只需創建一個列表,並返回它。

2

見我的答案在這裏:

總結:
VB.Net沒有屈服,而是用C#代碼轉換成一個狀態機實現產量幕後。 VB.Net的Static關鍵字還允許你在一個函數中存儲狀態,所以理論上你應該能夠實現一個類,允許你在用作方法的Static成員時編寫類似的代碼。

0

在幕後,編譯器創建一個枚舉類來完成這項工作。因爲VB.NET沒有實現這種模式,你必須創建自己的實現了IEnumerator(Of T)已

0

列出了輸出:2,4,8,16,32

在VB中,

Public Shared Function setofNumbers() As Integer() 

    Dim counter As Integer = 0 
    Dim results As New List(Of Integer) 
    Dim result As Integer = 1 
    While counter < 5 
     result = result * 2 
     results.Add(result) 
     counter += 1 
    End While 
    Return results.ToArray() 
End Function 

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
    For Each i As Integer In setofNumbers() 
     MessageBox.Show(i) 
    Next 
End Sub 

在C#

private void Form1_Load(object sender, EventArgs e) 
    { 
     foreach (int i in setofNumbers()) 
     { 
      MessageBox.Show(i.ToString()); 
     } 
    } 

    public static IEnumerable<int> setofNumbers() 
    { 
     int counter=0; 
     //List<int> results = new List<int>(); 
     int result=1; 
     while (counter < 5) 
     { 
      result = result * 2; 
      counter += 1; 
      yield return result; 
     } 
    } 
相關問題