CKTIS / C#
delegates and events: odniesienie praktyczne
delegates and events: odniesienie praktyczne: Delegat przechowuje wywoływalny kontrakt, a event ogranicza publikację listy subskrybentów do właściciela.
Wersja: C# language and .NET 10 reference runtime
Składnia
// delegates eventsDelegat przechowuje wywoływalny kontrakt, a event ogranicza publikację listy subskrybentów do właściciela.
Używaj callbacków i zdarzeń do luźnego powiadamiania z jawnym cyklem życia.
Subskrypcja utrzymuje referencję do odbiorcy; brak unsubscribe może powodować wyciek.
Wyjątek jednego handlera przerywa zwykłe multicast invocation.
Kompletny program rzeczywiście używa delegates and events; oczekiwany stdout to dokładnie 5.
Przykłady
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 source = new Source(); source.Changed += value => Console.WriteLine(value); source.Raise(5); sealed class Source { public event Action<int>? Changed; public void Raise(int value) => Changed?.Invoke(value); }
Wynik
5
Kompletny program rzeczywiście używa `delegates and events`; oczekiwany stdout to dokładnie `5`.