Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / C#

this: odniesienie praktyczne

this: odniesienie praktyczne: this odwołuje się do bieżącej instancji lub przekazuje jej konstrukcję do innego konstruktora.

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

Składnia

this /* grammar-specific form */

this odwołuje się do bieżącej instancji lub przekazuje jej konstrukcję do innego konstruktora.

Stosuj do rozróżnienia pola od parametru i spójnego constructor chaining.

Nie jest dostępne w static context; ucieczka this z konstruktora ujawnia niegotowy obiekt.

W struct this ma semantykę wartości i podlega ograniczeniom readonly.

Kompletny program rzeczywiście używa this; oczekiwany stdout to dokładnie 4.

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;

Console.WriteLine(new Box(4).Read()); sealed class Box { private readonly int value; public Box(int value) => this.value = value; public int Read() => this.value; }

Wynik

4

Kompletny program rzeczywiście używa `this`; oczekiwany stdout to dokładnie `4`.

Źródła