CKTIS / C#
foreach: praktická referencia
foreach: praktická referencia: foreach prechádza zdroj pomocou vzoru enumerátora; vygenerovaný blok finally uvoľní enumerátor iba vtedy, keď spĺňa vzor Dispose alebo IDisposable.
Verzia: C# language; verified against C# 14 reference
Syntax
foreach /* grammar-specific form */foreach prechádza zdroj pomocou vzoru enumerátora; vygenerovaný blok finally uvoľní enumerátor iba vtedy, keď spĺňa vzor Dispose alebo IDisposable.
Použite na sekvenčné čítanie bez ručného volania MoveNext.
Zmena kolekcie obvykle zneplatní enumerátor; iteračná premenná nie je index.
Prázdny zdroj telo preskočí; await foreach vyžaduje asynchrónny vzor.
Úplný program skutočne používa foreach; presne očakávaný stdout je 6.
Príklady
using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;
var sum = 0; foreach (var value in new[] { 1, 2, 3 }) sum += value; Console.WriteLine(sum);
Výsledok
6
Úplný program skutočne používa `foreach`; presne očakávaný stdout je `6`.