Skip to content

IT CSharp Keyword field

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: field

Manuale C# · Guida pratica

Si riferisce a un campo di proprietà generato automaticamente all'interno della sua funzione di accesso. Ti consente di combinare l'archiviazione automatica con la verifica.

Esempio semplice (Example.cs)

Salvare questo esempio separatamente come Example.cs. Eseguirlo indipendentemente dagli altri esempi di questa pagina.

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); } }

Risultato:

0

Sintassi

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

Sintassi C# 14. L'identificatore @field può fare riferimento al proprio membro con lo stesso nome.

Esempio 1: forma 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); } }

Esempio 2: un'altra forma pratica

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(); } }

Fonte ufficiale: Microsoft Impara.

Clone this wiki locally