Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / C#

remove: riferimento pratico

remove: riferimento pratico: remove definisce un accessor per annullare la sottoscrizione a un event e riceve il handler come value.

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

Sintassi

remove /* grammar-specific form */

remove definisce un accessor per annullare la sottoscrizione a un event e riceve il handler come value.

Usalo con add quando l’archiviazione delle sottoscrizioni richiede controllo personalizzato.

L’asimmetria tra add e remove causa perdite o unsubscribe inefficace.

La rimozione di un handler assente deve avere un comportamento definito consapevolmente.

Il programma completo usa realmente remove; lo stdout esatto atteso è done.

Esempi

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(); Action handler = () => Console.WriteLine("bad"); source.Changed += handler; source.Changed -= handler; source.Raise(); Console.WriteLine("done");
sealed class Source { private Action? changed; public event Action Changed { add => changed += value; remove => changed -= value; } public void Raise() => changed?.Invoke(); }

Risultato

done

Il programma completo usa realmente `remove`; lo stdout esatto atteso è `done`.

Fonti