しかし、goto
それは醜く、常に可能であるとは限りません。ループをメソッド (または anon-method) に配置return
して、メイン コードに戻るために使用することもできます。
// goto
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
goto Foo; // yeuck!
}
}
Foo:
Console.WriteLine("Hi");
対:
// anon-method
Action work = delegate
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
return; // exits anon-method
}
}
};
work(); // execute anon-method
Console.WriteLine("Hi");
C# 7 では、「ローカル関数」を取得する必要があることに注意してください。これは (構文 tbd など)、次のように機能する必要があることを意味します。
// local function (declared **inside** another method)
void Work()
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
return; // exits local function
}
}
};
Work(); // execute local function
Console.WriteLine("Hi");