Baza znanjaIzpitno središče
SLSlovenščina
Izberi jezik13

CKTIS / C#

Delegati Func z n-terico in akumulatorjem ter preverjanje velikosti

En delegat sporoči uspeh pretvorbe, drugi posodablja akumulator, zahtevana velikost zunaj dovoljenega obsega pa sproži izjemo.

Različica: C# 12 and .NET 8; later runtimes may add compatible features

Sintaksa

System.Func<TSource, (bool Success, TResult Value)> convert;
System.Func<TAcc, T, TAcc> accumulate;

if (size < 0 || size > source.Count)
    throw new System.ArgumentOutOfRangeException(nameof(size), size, "Size must be between zero and the source count.");

Func<TSource,(bool,TResult)> je delegat iz imenskega prostora System. Sprejme en argument tipa TSource in vrne eno vrednost: n-terico vrednostnega tipa System.ValueTuple<bool,TResult>, ne dveh parametrov out. Imena polj, kot sta Success in Value, so neobvezna; rezultat lahko razstaviš z var (success, value). Pomen zastavice določa pogodba delegata: tukaj false pomeni, da vrednost prezreš, true pa dovoljuje uporabo vrednosti, tudi če je enaka privzeti vrednosti tipa.

Func<TAcc,T,TAcc> je drug tip delegata iz System. Sprejme trenutni akumulator tipa TAcc in element tipa T ter vrne naslednji akumulator tipa TAcc. Zadnji tipski argument Func je tip vrnjene vrednosti. V FoldPrefix je T tip rezultata pretvorbe (TResult v prvem zapisu). Metoda začne z seed, po vrsti obdela prvih size elementov in akumulator posodobi le po uspešni pretvorbi. V size se štejejo tudi zavrnjeni elementi.

FoldPrefix je metoda iz primera, ne del API-ja platforme .NET. Veljavna velikost je od 0 do vključno source.Count. Pri ničli metoda vrne seed, ne da bi poklicala katerega od delegatov. Če velja size < 0 || size > source.Count, sproži System.ArgumentOutOfRangeException, preden dostopa do katerega koli elementa prek indeksa ali pokliče delegata. Konstruktor s tremi argumenti po vrsti sprejme ime parametra (nameof(size)), neveljavno vrednost (size) in sporočilo z opisom obsega. Ime in vrednost sta dostopna prek ParamName in ActualValue.

Primeri

using System;
using System.Collections.Generic;
using System.Globalization;

string[] items = { "2", "bad", "3", "100" };
Func<string, (bool Success, int Value)> convert = text =>
{
    bool success = int.TryParse(text, NumberStyles.Integer,
        CultureInfo.InvariantCulture, out int value);
    return (success, value);
};
Func<int, int, int> accumulate = (sum, value) => sum + value;

Console.WriteLine(FormattableString.Invariant($"size 3: {FoldPrefix(items, 3, 10, convert, accumulate)}"));
Console.WriteLine(FormattableString.Invariant($"size 0: {FoldPrefix(items, 0, 10, convert, accumulate)}"));

try
{
    FoldPrefix(items, 5, 10, convert, accumulate);
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine(FormattableString.Invariant($"out of range: {ex.ParamName}={ex.ActualValue}"));
}

static TAcc FoldPrefix<TSource, T, TAcc>(
    IReadOnlyList<TSource> source, int size, TAcc seed,
    Func<TSource, (bool Success, T Value)> convert,
    Func<TAcc, T, TAcc> accumulate)
{
    ArgumentNullException.ThrowIfNull(source);
    ArgumentNullException.ThrowIfNull(convert);
    ArgumentNullException.ThrowIfNull(accumulate);

    if (size < 0 || size > source.Count)
        throw new ArgumentOutOfRangeException(nameof(size), size,
            "Size must be between zero and the source count.");

    TAcc acc = seed;
    for (int i = 0; i < size; i++)
    {
        var (success, value) = convert(source[i]);
        if (success)
            acc = accumulate(acc, value);
    }
    return acc;
}

Rezultat

size 3: 15
size 0: 10
out of range: size=5

Konzolni primer za C# 12 in .NET 8: velikost 3 da 15 (10 + 2 + 3), ker je `bad` preskočen, `100` pa je zunaj predpone. Velikost 0 da 10. Velikost 5 je pri štirih elementih neveljavna; program izpiše ime parametra in njegovo vrednost, ne sporočila izjeme.

Povezane lekcije

  • C# · Lekcija 29 · Napredna · Različica: 3

Viri