Skip to content

FR CSharp Keyword field

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: field

Manuel C# · Guide pratique

Fait référence à un champ de propriété généré automatiquement à l'intérieur de son accesseur. Vous permet de combiner le stockage automatique avec la vérification.

Exemple simple (Example.cs)

Enregistrez cet exemple séparément dans Example.cs. Exécutez-le indépendamment des autres exemples de cette page.

Example.cs:

// PROJECT-EXAMPLE
var item = new Item();
item.Count = -2;
System.Console.WriteLine(item.Count);
class Item { public int Count { get; set => field = System.Math.Max(0, value); } }

Résultat:

0

Syntaxe

public int Count { get; set => field = Math.Max(0, value); }

Syntaxe C# 14. L'identifiant @field peut faire référence à son propre membre portant le même nom.

Exemple 1 : formulaire de base

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Meter meter = new() { Count = -3 };
        Console.WriteLine(meter.Count);
    }
}
public class Meter { public int Count { get; set => field = Math.Max(0, value); } }

Exemple 2 : une autre forme pratique

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Profile profile = new() { Name = " archer " };
        Console.WriteLine(profile.Name);
    }
}
public class Profile { public string Name { get => field ?? ""; set => field = value.Trim(); } }

Source officielle : Microsoft Apprendre.

Clone this wiki locally