vb.net에서 ienumerable 함수에 대한 수율 수익률을 구현할 수 있습니까? [복제하다

StackOverflow https://stackoverflow.com/questions/875587

문제

가능한 복제 :
vb.net의 수율

C#에서, 반환하는 함수를 작성할 때 IEnumerble<>, 당신이 사용할 수있는 yield return 열거의 단일 항목을 반환합니다 yield break; 나머지 항목을 의미하지 않습니다. 같은 일을하는 VB.NET 구문은 무엇입니까?

The의 예 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;
}

이것 C#을 VB.NET 도구로 변환하십시오 "수율 확대는 지원되지 않은"오류를 제공합니다.

도움이 되었습니까?

해결책

현재 언어 구문 수준에서 VB.NET의 C#의 수율 수익률과 동등한 것은 없습니다.

그러나 Bill McCarthy의 MSDN Magazine에서 VB.NET 9.0에서 유사한 패턴을 구현하는 방법에 대한 최근의 글이있었습니다.

다른 팁

새로운 비동기 CTP 지원을 포함합니다 Yield vb.net에서.

보다 Visual Basic의 반복자 사용에 대한 정보.

여기에서 내 답변을 참조하십시오.

요약:
vb.net에는 수율이 없지만 C#은 코드를 해당 장면 뒤의 상태 머신으로 변환하여 수율을 구현합니다. vb.net 's Static 키워드는 또한 함수 내에 상태를 저장할 수 있으므로 이론적으로는 이론적으로는 Static 방법의 구성원.

vb.net에서 수익률 반환이 없음 :( 목록을 작성하고 반환하십시오.

무대 뒤에서 컴파일러는 작업을 수행하기 위해 열거 자 클래스를 만듭니다. vb.net 은이 패턴을 구현하지 않으므로 ienumerator (t)의 자체 구현을 만들어야합니다.

아래는 출력을 제공합니다 : 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;
        }
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top