yield
Iteratoren (IEnumerable) sind ein .NET-Entwurfsmuster zur Erzeugung aufzählbarer Mengen, die mit for…each durchlaufen werden können. Das Schlüsselwort yield vereinfacht die Iterator-Implementierung erheblick. yield liefert ähnlich wie return einen Wert an den Aufrufer zurück.
C# Programm mit foreach, yield, returnusing System;
namespace yellowsubroutine
{
public class Program
{
static void Main()
{
foreach (int value in ComputeSquares(2, 30))
{
Console.Write(value);
Console.Write(" ");
}
Console.WriteLine();
}
public static System.Collections.Generic.IEnumerable<int> ComputeSquares(int min, int max)
{
for (int i = min; i <= max; ++i)
{
yield return i * i;
}
}
}
}
C# Programm unifiziert eine Variable.using System;
using System.Collections.Generic;
namespace yellowsubroutine
{
class UnifyingVariable
{
public object _value;
public bool _isBound = false;
public IEnumerable<bool> unify(object arg)
{
if (!_isBound)
{
_value = arg;
_isBound = true;
yield return false;
// Remove the binding.
_isBound = false;
}
else if (_value.Equals(arg))
yield return false;
}
}
class Tutorial1
{
static IEnumerable<bool> personWithUnify
(UnifyingVariable Person)
{
foreach (bool l1 in Person.unify("Chelsea"))
yield return false;
foreach (bool l1 in Person.unify("Hillary"))
yield return false;
foreach (bool l1 in Person.unify("Bill"))
yield return false;
}
static void Main(string[] args)
{
Console.WriteLine("Names using UnifyingVariable:");
UnifyingVariable Person = new UnifyingVariable();
foreach (bool l1 in personWithUnify(Person))
Console.WriteLine(Person._value);
}
}
}