Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / C#

with: referencia práctica

with: referencia práctica: with crea una copia no destructiva solo para una record class, un tipo anónimo o un tipo valor distinto de void, incluidos struct y tuple.

Versión: C# language; verified against C# 14 reference

Sintaxis

with /* grammar-specific form */

with crea una copia no destructiva solo para una record class, un tipo anónimo o un tipo valor distinto de void, incluidos struct y tuple.

Úsalo para producir la siguiente versión de un valor sin mutar el original.

La copia es superficial, por lo que los miembros de referencia siguen compartidos.

Los required members y reglas init deben cumplirse; una clase normal que no sea record no puede habilitar with añadiendo un protocolo.

El programa completo usa realmente with; su stdout esperado exacto es 2.

Ejemplos

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.Level); sealed record Person(string Name, int Level);

Resultado

2

El programa completo usa realmente `with`; su stdout esperado exacto es `2`.

Fuentes