yield (C# リファレンス)yield (C# Reference)
ステートメントで yield
コンテキスト キーワードを使用した場合、メソッド、演算子、または get
アクセサーが反復子であることを示します。When you use the yield
contextual keyword in a statement, you indicate that the method, operator, or get
accessor in which it appears is an iterator. yield
を使用して反復子を定義すると、カスタム コレクション型の IEnumerator<T> および IEnumerable パターンを実装するときに明示的な余分なクラス (列挙の状態を保持するクラス。たとえば IEnumerator を参照) が不要になります。Using yield
to define an iterator removes the need for an explicit extra class (the class that holds the state for an enumeration, see IEnumerator<T> for an example) when you implement the IEnumerable and IEnumerator pattern for a custom collection type.
yield
ステートメントの 2 つの形式を次の例に示します。The following example shows the two forms of the yield
statement.
yield return <expression>;
yield break;
コメントRemarks
各要素を 1 つずつ返すには、yield return
ステートメントを使用します。You use a yield return
statement to return each element one at a time.
foreach ステートメントまたは LINQ クエリを使用することにより、Iterator メソッドを処理します。You consume an iterator method by using a foreach statement or LINQ query. foreach
ループの各イテレーションは、Iterator メソッドを呼び出します。Each iteration of the foreach
loop calls the iterator method. yield return
ステートメントが Iterator メソッドに到達すると、expression
が返され、コードの現在の位置が保持されます。When a yield return
statement is reached in the iterator method, expression
is returned, and the current location in code is retained. 次回、Iterator 関数が呼び出されると、この位置から実行が再開されます。Execution is restarted from that location the next time that the iterator function is called.
yield break
ステートメントを使用すると、反復を終了できます。You can use a yield break
statement to end the iteration.
反復子について詳しくは、「Iterators」をご覧ください。For more information about iterators, see Iterators.
Iterator メソッドと get アクセサーIterator methods and get accessors
反復子の宣言は、次の要件を満たす必要があります。The declaration of an iterator must meet the following requirements:
戻り値の型は、IEnumerable、IEnumerable<T>、IEnumerator、または IEnumerator<T> であることが必要です。The return type must be IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>.
この宣言には、in、ref、out パラメーターを含めることはできません。The declaration can't have any in ref or out parameters.
yield
または IEnumerable を返す反復子の IEnumerator 型は object
です。The yield
type of an iterator that returns IEnumerable or IEnumerator is object
. 反復子が IEnumerable<T> または IEnumerator<T> を返す場合、yield return
ステートメント内の式の型から、ジェネリック型パラメーターへの暗黙的な変換が存在する必要があります。If the iterator returns IEnumerable<T> or IEnumerator<T>, there must be an implicit conversion from the type of the expression in the yield return
statement to the generic type parameter .
次の特性を持つメソッドに yield return
ステートメントまたは yield break
ステートメントを含めることはできません。You can't include a yield return
or yield break
statement in methods that have the following characteristics:
匿名メソッド。Anonymous methods. 詳しくは、「匿名メソッド」をご覧ください。For more information, see Anonymous Methods.
unsafe ブロックを含むメソッド。Methods that contain unsafe blocks. 詳しくは、「unsafe」をご覧ください。For more information, see unsafe.
例外処理Exception handling
yield return
ステートメントは、try-catch ブロックに配置することはできません。A yield return
statement can't be located in a try-catch block. yield return
ステートメントは、try-finally ステートメントの try ブロックに配置できます。A yield return
statement can be located in the try block of a try-finally statement.
yield break
ステートメントは、try ブロックまたは catch ブロックには配置できますが、finally ブロックには配置できません。A yield break
statement can be located in a try block or a catch block but not a finally block.
foreach
本体 (Iterator メソッドの外部) で例外がスローされた場合、Iterator メソッドの finally
ブロックが実行されます。If the foreach
body (outside of the iterator method) throws an exception, a finally
block in the iterator method is executed.
技術的な実装Technical implementation
次のコードは、iterator メソッドから IEnumerable<string>
を返した後、要素を反復処理します。The following code returns an IEnumerable<string>
from an iterator method and then iterates through its elements.
IEnumerable<string> elements = MyIteratorMethod();
foreach (string element in elements)
{
...
}
MyIteratorMethod
への呼び出しでは、メソッドの本体は実行されません。The call to MyIteratorMethod
doesn't execute the body of the method. この呼び出しでは、IEnumerable<string>
が elements
変数に返されます。Instead the call returns an IEnumerable<string>
into the elements
variable.
foreach
ループの反復処理では、MoveNext について elements
メソッドが呼び出されます。On an iteration of the foreach
loop, the MoveNext method is called for elements
. この呼び出しでは、次の MyIteratorMethod
ステートメントに到達するまで、yield return
の本体が実行されます。This call executes the body of MyIteratorMethod
until the next yield return
statement is reached. yield return
ステートメントによって返される式は、ループ本体による処理に対する element
変数の値だけでなく、IEnumerable<string>
である、elements
の Current プロパティも決定します。The expression returned by the yield return
statement determines not only the value of the element
variable for consumption by the loop body but also the Current property of elements
, which is an IEnumerable<string>
.
foreach
ループの以降の各反復処理では、反復子本体の実行が中断した場所から続行し、yield return
ステートメントに到達したときに再度停止します。On each subsequent iteration of the foreach
loop, the execution of the iterator body continues from where it left off, again stopping when it reaches a yield return
statement. iterator メソッドまたは foreach
ステートメントの最後に到達すると、yield break
ループは完了します。The foreach
loop completes when the end of the iterator method or a yield break
statement is reached.
例Example
次の例では、yield return
ループ内に for
ステートメントが含まれます。The following example has a yield return
statement that's inside a for
loop. Main
メソッド内の foreach
ステートメント本体の各反復処理では、Power
Iterator 関数が呼び出されます。Each iteration of the foreach
statement body in the Main
method creates a call to the Power
iterator function. Iterator 関数を呼び出すごとに、yield return
ステートメントの次の実行に進みます。これは、for
ループの次の反復処理で行われます。Each call to the iterator function proceeds to the next execution of the yield return
statement, which occurs during the next iteration of the for
loop.
Iterator メソッドの戻り値の型は IEnumerable であり、これは反復子インターフェイス型です。The return type of the iterator method is IEnumerable, which is an iterator interface type. Iterator メソッドが呼び出されると、数値の累乗を含む列挙可能なオブジェクトが返されます。When the iterator method is called, it returns an enumerable object that contains the powers of a number.
public class PowersOf2
{
static void Main()
{
// Display powers of 2 up to the exponent of 8:
foreach (int i in Power(2, 8))
{
Console.Write("{0} ", i);
}
}
public static System.Collections.Generic.IEnumerable<int> Power(int number, int exponent)
{
int result = 1;
for (int i = 0; i < exponent; i++)
{
result = result * number;
yield return result;
}
}
// Output: 2 4 8 16 32 64 128 256
}
例Example
次の例は、反復子である get
アクセサーを示しています。The following example demonstrates a get
accessor that is an iterator. この例では、各 yield return
ステートメントがユーザー定義クラスのインスタンスを返します。In the example, each yield return
statement returns an instance of a user-defined class.
public static class GalaxyClass
{
public static void ShowGalaxies()
{
var theGalaxies = new Galaxies();
foreach (Galaxy theGalaxy in theGalaxies.NextGalaxy)
{
Debug.WriteLine(theGalaxy.Name + " " + theGalaxy.MegaLightYears.ToString());
}
}
public class Galaxies
{
public System.Collections.Generic.IEnumerable<Galaxy> NextGalaxy
{
get
{
yield return new Galaxy { Name = "Tadpole", MegaLightYears = 400 };
yield return new Galaxy { Name = "Pinwheel", MegaLightYears = 25 };
yield return new Galaxy { Name = "Milky Way", MegaLightYears = 0 };
yield return new Galaxy { Name = "Andromeda", MegaLightYears = 3 };
}
}
}
public class Galaxy
{
public String Name { get; set; }
public int MegaLightYears { get; set; }
}
}
C# 言語仕様C# language specification
詳細については、「C# 言語の仕様」を参照してください。For more information, see the C# Language Specification. 言語仕様は、C# の構文と使用法に関する信頼性のある情報源です。The language specification is the definitive source for C# syntax and usage.
関連項目See also
フィードバック
お客様のご意見をお寄せください。 お寄せいただく内容の種類を選択:
このフィードバック システムは、GitHub Issues を利用して構築されています。 詳しくは、ブログをご覧ください。
フィードバックを読み込んでいます...