struct Point { // champs public int x, y; }Et voici un exemple un peut plus complet :
Code | Résultat | Remarques |
using System; namespace Exemples { struct Point { // champs public string nom; public int x, y; // constructeur public Point(string nom, int x, int y) { this.nom = nom; this.x = x; this.y = y; } // méthode public void AffichePoint() { Console.WriteLine(nom + "(" + x +", " + y + ")"); } } class Structures { static void Main(string[] args) { // utilisation du constructeur par défaut Point p1 = new Point(); p1.AffichePoint(); // affiche (0, 0) // utilisation du constructeur avec 3 arguments Point p2 = new Point("P2", 33, 33); p2.AffichePoint(); // affiche P2(33, 33) Point p3; // initialisation sans constructeur p3.nom = "P3"; p3.x = 33; p3.y = 91; p3.AffichePoint(); // affiche P3(33, 91) // tableau de structures Point[] points = new Point[3]; points[0] = p1; points[1] = p2; points[2] = p3; foreach (Point p in points) p.AffichePoint(); // affiche tout ce qui a été affiché avant... Console.ReadKey(); } } } |
(0, 0) P2(33, 33) P3(33, 91) (0, 0) P2(33, 33) P3(33, 91) |
Pour créer une structure, vous pouvez utiliser l'opérateur new qui initialisera tous les membres de la structure. Si vous n'utilisez pas l'opérateur new, vous devrez initialiser les membres de la structure vous-même. Vous pouvez également utiliser la syntaxe de déclaration de tableau pour créer un tableau de structures. |
Pour plus d'information :
ValueType, classe : http://msdn.microsoft.com/fr-fr/library/system.valuetype.aspx