Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / C#

records and equality: referência prática

records and equality: referência prática: Um record fornece semântica de valor e suporte a with; apenas um record posicional sintetiza Deconstruct automaticamente.

Versão: C# language and .NET 10 reference runtime

Sintaxe

// records

Um record fornece semântica de valor e suporte a with; apenas um record posicional sintetiza Deconstruct automaticamente.

Usa-o para dados cuja identidade resulta dos componentes.

A imutabilidade do record é superficial; uma propriedade pode referenciar um objeto mutável.

A igualdade inclui o tipo runtime e with copia referências dos componentes.

O programa completo usa realmente records and equality; o stdout exato esperado é Ada:2.

Exemplos

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 first = new Person("Ada", 1); var second = first with { Level = 2 }; Console.WriteLine($"{second.Name}:{second.Level}"); sealed record Person(string Name, int Level);

Resultado

Ada:2

O programa completo usa realmente `records and equality`; o stdout exato esperado é `Ada:2`.

Fontes