Znalostní bázeCentrum zkoušek
CSČeština
Vybrat jazyk13

CKTIS / C#

foreach: praktická reference

foreach: praktická reference: foreach prochází zdroj pomocí vzoru enumerátoru; vygenerovaný blok finally uvolní enumerátor jen tehdy, když splňuje vzor Dispose nebo IDisposable.

Verze: C# language; verified against C# 14 reference

Syntaxe

foreach /* grammar-specific form */

foreach prochází zdroj pomocí vzoru enumerátoru; vygenerovaný blok finally uvolní enumerátor jen tehdy, když splňuje vzor Dispose nebo IDisposable.

Použijte pro sekvenční čtení bez ručního volání MoveNext.

Změna kolekce obvykle zneplatní enumerátor; iterační proměnná není index.

Prázdný zdroj tělo přeskočí; await foreach vyžaduje asynchronní vzor.

Úplný program skutečně používá foreach; přesně očekávaný stdout je 6.

Pří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ýsledek

6

Úplný program skutečně používá `foreach`; přesně očekávaný stdout je `6`.

Zdroje