Skip to content

IT CSharp Classes

Codex edited this page Oct 11, 2026 · 2 revisions

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

Classi, oggetti e costruttori

Manuale C# · Esempi UO

Una classe descrive lo stato e il comportamento di un oggetto. new crea un'istanza, il costruttore imposta lo stato iniziale, i campi memorizzano i dati, le proprietà controllano l'accesso, i metodi eseguono azioni. this denota l'istanza corrente.

Esempio semplice (Example.cs)

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

Example.cs:

// PROJECT-EXAMPLE
var player = new Player();
System.Console.WriteLine(player.Name);
class Player { public string Name = "Archer"; }

Risultato:

Archer
sealed class Report
{
    public string Name { get; }
    public int Count { get; private set; }
    public Report(string name) => Name = name;
    public void Add() => Count++;
    public override string ToString() => $"{Name}: {Count}";
}

var report = new Report("Attempts");
report.Add();
report.Add();
UO.Print(report.ToString());

In un normale progetto .cs, è conveniente separare i tipi in file. .csx può dichiarare i propri tipi, ma il codice all'interno della classe non ottiene automaticamente l'oggetto UO: passalo esplicitamente API o il delegato desiderato.

sealed class MessageWriter
{
    private readonly Action<string> write;
    public MessageWriter(Action<string> write) => this.write = write;
    public void Send(string text) => write(text);
}

var writer = new MessageWriter(text => UO.Print(text));
writer.Send("A class uses the current session API");

Documentazione ufficiale: Classi, oggetti e costruttori - Microsoft Learn.

Clone this wiki locally