Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Costruttori di Struct | Struct e Enumeratori
C# Oltre le Basi

bookCostruttori di Struct

Un costruttore è un metodo che viene eseguito automaticamente quando viene creato un nuovo oggetto.

La sintassi di un costruttore è simile a quella di un metodo, ma si omette il returnType poiché un costruttore non restituisce alcun valore:

index.cs

index.cs

copy
1234567891011
struct structureName { // ... fields (optional) public structureName(parameter1, parameter2, ...) { // code } // ... methods (optional) }

I seguenti punti sono importanti da ricordare riguardo la sintassi del costruttore:

  1. Il nome del costruttore è uguale al nome della struttura;
  2. Un costruttore non ha alcun valore di ritorno.

Il seguente programma dimostra come il costruttore venga chiamato ogni volta che viene creato un oggetto:

index.cs

index.cs

copy
12345678910111213141516171819
using System; struct Player { public Player() { Console.WriteLine($"New Player Object Created"); } } class Program { static void Main(string[] args) { Player player1 = new Player(); Player player2 = new Player(); Player player3 = new Player(); } }
Note
Nota

Se si utilizza una versione di C# precedente a C# 10, potrebbe verificarsi un errore in fase di compilazione. Si consiglia di utilizzare C# 10 o una versione successiva. Se non si desidera passare a una versione più recente, è importante notare che l'utilizzo dei costruttori sarà più limitato. Ad esempio, non è possibile creare un costruttore senza parametri nelle versioni precedenti.

Aggiungere un campo a Player chiamato id, che sarà un identificatore univoco per quell'oggetto, in modo che ogni oggetto abbia un valore diverso per id. Partirà da 0 e verrà incrementato. Per ottenere questo risultato, è necessario creare una variabile globale chiamata totalPlayers.

index.cs

index.cs

copy
12345678910111213141516171819202122232425262728
using System; class ConsoleApp { // We use the term 'static' when declaring variables directly under class // This will be explained in much more detail in later sections. public static int totalPlayers = 0; // This time we create put the struct inside the `ConsoleApp` class // This is to be able to use the `totalPlayers` variable easily. struct Player { public int id; public Player() { id = totalPlayers++; Console.WriteLine($"New Player Object Created With ID {id}"); } } static void Main(string[] args) { Player player1 = new Player(); Player player2 = new Player(); Player player3 = new Player(); } }

Nel codice sopra, la struct è stata inserita all'interno della classe Program per poter accedere alla variabile 'totalPlayers' dal costruttore.

È possibile passare dati a un costruttore durante la creazione di un nuovo oggetto utilizzando la seguente sintassi:

structureName variableName = new structureName(argument1, argument2, …);

Segue un esempio pratico di utilizzo:

index.cs

index.cs

copy
1234567891011121314151617181920212223242526272829
using System; struct Coordinate3D { public double x; public double y; public double z; public Coordinate3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public void displayValue() { Console.WriteLine($"{this.x}, {this.y}, {this.z}"); } } class ConsoleApp { static void Main(string[] args) { Coordinate3D coord1 = new Coordinate3D(3, 5, 7); coord1.displayValue(); } }

Analizziamo il codice passo dopo passo.

Per prima cosa, è stato creato un costruttore e all'interno del costruttore sono stati assegnati i valori passati x, y, z ai campi x, y e z:

index.cs

index.cs

copy
123456
public Coordinate3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; }

All'interno del metodo Main, è stato creato un nuovo oggetto Coordinate3D e sono stati passati 3, 5 e 7 come x, y e z tramite il costruttore.

index.cs

index.cs

copy
1
Coordinate3D coord1 = new Coordinate3D(3, 5, 7);

Per verificare se i campi sono stati inizializzati correttamente dal costruttore, è stato utilizzato il metodo displayValue:

index.cs

index.cs

copy
1
coord1.displayValue();

L'output ha dimostrato che i campi sono stati aggiornati con successo.

I costruttori sono molto utili quando si desidera inizializzare oggetti con alcuni dati o per eseguire alcune operazioni iniziali quando un oggetto viene creato.

question mark

Quando vengono chiamati i costruttori?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 2. Capitolo 8

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Suggested prompts:

Can you explain more about how constructors work in different programming languages?

What happens if I don't define a constructor in my structure or class?

Can you show an example of using multiple constructors with different parameters?

Awesome!

Completion rate improved to 2.04

bookCostruttori di Struct

Scorri per mostrare il menu

Un costruttore è un metodo che viene eseguito automaticamente quando viene creato un nuovo oggetto.

La sintassi di un costruttore è simile a quella di un metodo, ma si omette il returnType poiché un costruttore non restituisce alcun valore:

index.cs

index.cs

copy
1234567891011
struct structureName { // ... fields (optional) public structureName(parameter1, parameter2, ...) { // code } // ... methods (optional) }

I seguenti punti sono importanti da ricordare riguardo la sintassi del costruttore:

  1. Il nome del costruttore è uguale al nome della struttura;
  2. Un costruttore non ha alcun valore di ritorno.

Il seguente programma dimostra come il costruttore venga chiamato ogni volta che viene creato un oggetto:

index.cs

index.cs

copy
12345678910111213141516171819
using System; struct Player { public Player() { Console.WriteLine($"New Player Object Created"); } } class Program { static void Main(string[] args) { Player player1 = new Player(); Player player2 = new Player(); Player player3 = new Player(); } }
Note
Nota

Se si utilizza una versione di C# precedente a C# 10, potrebbe verificarsi un errore in fase di compilazione. Si consiglia di utilizzare C# 10 o una versione successiva. Se non si desidera passare a una versione più recente, è importante notare che l'utilizzo dei costruttori sarà più limitato. Ad esempio, non è possibile creare un costruttore senza parametri nelle versioni precedenti.

Aggiungere un campo a Player chiamato id, che sarà un identificatore univoco per quell'oggetto, in modo che ogni oggetto abbia un valore diverso per id. Partirà da 0 e verrà incrementato. Per ottenere questo risultato, è necessario creare una variabile globale chiamata totalPlayers.

index.cs

index.cs

copy
12345678910111213141516171819202122232425262728
using System; class ConsoleApp { // We use the term 'static' when declaring variables directly under class // This will be explained in much more detail in later sections. public static int totalPlayers = 0; // This time we create put the struct inside the `ConsoleApp` class // This is to be able to use the `totalPlayers` variable easily. struct Player { public int id; public Player() { id = totalPlayers++; Console.WriteLine($"New Player Object Created With ID {id}"); } } static void Main(string[] args) { Player player1 = new Player(); Player player2 = new Player(); Player player3 = new Player(); } }

Nel codice sopra, la struct è stata inserita all'interno della classe Program per poter accedere alla variabile 'totalPlayers' dal costruttore.

È possibile passare dati a un costruttore durante la creazione di un nuovo oggetto utilizzando la seguente sintassi:

structureName variableName = new structureName(argument1, argument2, …);

Segue un esempio pratico di utilizzo:

index.cs

index.cs

copy
1234567891011121314151617181920212223242526272829
using System; struct Coordinate3D { public double x; public double y; public double z; public Coordinate3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public void displayValue() { Console.WriteLine($"{this.x}, {this.y}, {this.z}"); } } class ConsoleApp { static void Main(string[] args) { Coordinate3D coord1 = new Coordinate3D(3, 5, 7); coord1.displayValue(); } }

Analizziamo il codice passo dopo passo.

Per prima cosa, è stato creato un costruttore e all'interno del costruttore sono stati assegnati i valori passati x, y, z ai campi x, y e z:

index.cs

index.cs

copy
123456
public Coordinate3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; }

All'interno del metodo Main, è stato creato un nuovo oggetto Coordinate3D e sono stati passati 3, 5 e 7 come x, y e z tramite il costruttore.

index.cs

index.cs

copy
1
Coordinate3D coord1 = new Coordinate3D(3, 5, 7);

Per verificare se i campi sono stati inizializzati correttamente dal costruttore, è stato utilizzato il metodo displayValue:

index.cs

index.cs

copy
1
coord1.displayValue();

L'output ha dimostrato che i campi sono stati aggiornati con successo.

I costruttori sono molto utili quando si desidera inizializzare oggetti con alcuni dati o per eseguire alcune operazioni iniziali quando un oggetto viene creato.

question mark

Quando vengono chiamati i costruttori?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 2. Capitolo 8
some-alt