Maison  >  Article  >  développement back-end  >  Pile C#

Pile C#

WBOY
WBOYoriginal
2024-09-03 15:30:28538parcourir

La collection d'objets qui est représentée par le dernier entré et le premier sorti est appelée une pile et c'est une collection qui augmente avec l'ajout d'éléments à la pile selon les besoins du programme, c'est donc une collection dynamique et des éléments du même type et des types différents peuvent être stockés dans la pile et le processus d'ajout d'un élément à la pile est appelé pousser l'élément vers la pile et le processus de suppression d'un élément de la pile est appelé extraire l'élément de la pile et cette pile relève de Systems. Espace de noms des collections.

Syntaxe :

La syntaxe de C# Stack est la suivante :

Stack stack_name = new Stack();

Où stack_name est le nom de la stack.l

Fonctions de Stack en C#

  • Chaque fois que nous avons besoin d'accéder aux éléments de la pile dans l'ordre du dernier entré et du premier sorti, nous utilisons la collection d'objets appelée Stack.
  • Le processus d'ajout d'un élément à la pile est appelé pousser les éléments vers la pile et le processus de suppression d'un élément de la pile est appelé extraire un élément de la pile.
  • La pile est une collection dynamique d'éléments car la taille de la pile augmente avec l'ajout d'éléments à la pile.
  • Le nombre d'éléments qu'une pile peut contenir est appelé la capacité de la pile. À mesure que la taille de la pile augmente avec l'ajout d'éléments à la pile, la capacité de la pile augmente également grâce à la réallocation.
  • Il peut y avoir des éléments en double autorisés dans la pile.
  • Null est accepté par la pile comme valeur valide pour le type et les références.

Il existe plusieurs constructeurs dans Stack en C#. Ce sont :

  • Stack() : Une nouvelle instance de la classe stack est initialisée qui est vide dont la capacité initiale est la capacité par défaut.
  • Stack(ICollection) : Une nouvelle instance de la classe stack est initialisée et se compose d'éléments extraits d'une collection spécifiée en tant que paramètre et la capacité initiale est la même que le nombre d'éléments pris de la collection spécifiée en paramètre.
  • Stack(Int32) : Une nouvelle instance de la classe stack est initialisée qui est vide dont la capacité initiale est soit la capacité initiale spécifiée en paramètre, soit la capacité initiale qui est par défaut.

Méthodes dans la pile C#

Il existe plusieurs méthodes dans Stack en C#. Ce sont :

  • Clear() : Les objets de la pile sont supprimés à l'aide de la méthode Clear().
  • Push(Object) : Un objet spécifié en paramètre est inséré en haut de la pile à l'aide de la méthode Push(Object).
  • Contains(Object) : La méthode Contains(Object) est utilisée pour déterminer si un élément est présent dans la pile.
  • Peek() : L'objet spécifié en haut de la pile est renvoyé mais n'est pas supprimé à l'aide de la méthode Peek().
  • Pop() : L'objet spécifié en haut de la pile est renvoyé et est supprimé à l'aide de la méthode Pop().

Exemples

Voici les exemples de pile c# :

Exemple n°1

Considérez l'exemple de programme ci-dessous pour démontrer la méthode Push(), la méthode Pop(), la méthode Peek(), la méthode Contains() et la méthode Clear() :

Code :

using System;
using System.Collections;
//a class called program is defined
class program
{
//main method is called
public static void Main()
{
//a new stack is created
Stack mystk = new Stack();
//Adding the elements to the newly created stack
mystk.Push("India");
mystk.Push("USA");
mystk.Push("Canada");
mystk.Push("Germany");
//displaying the elements of the stack using foreach loop
Console.Write("The elements in the Stack are : ");
foreach(varele in mystk)
{
Console.WriteLine(ele);
}
//using contains() method to check if an element is present in the stack or not
Console.WriteLine(mystk.Contains("Germany"));
// The count of the elements in the stack is displayed
Console.Write("The count of elements in the Stack are : ");
Console.WriteLine(mystk.Count);
// displaying the top most element of the stack using Peek() method
Console.WriteLine("The topmost element in the stack is  : " + mystk.Peek());
//Using pop() method to remove the top element in the stack
Console.WriteLine("the element of the stack that is going to be removed" + " is: {0}",mystk.Pop());
Console.Write("The elements in the Stack after using pop() method are : ");
foreach(var el in mystk)
{
Console.WriteLine(el);
}
Console.Write("The count of elements in the Stack after using pop() method is : ");
Console.WriteLine(mystk.Count);
//using Clear() method to remove all the elements in the stack
mystk.Clear();
Console.Write("The count of elements in the Stack after using Clear() method is : ");
Console.WriteLine(mystk.Count);
}
}

Sortie :

Pile C#

Dans le programme ci-dessus, une classe appelée programme est définie. Ensuite, la méthode principale est appelée. Ensuite, une nouvelle pile est créée. Ensuite, les éléments sont ajoutés dans la pile nouvellement créée à l'aide de la méthode Push(). Ensuite, les éléments de la pile nouvellement créée sont affichés à l'aide de la boucle foreach. Ensuite, la méthode contain() est utilisée pour vérifier si un élément est présent ou non dans la pile. Ensuite, le nombre d'éléments dans la pile est affiché à l'aide de la méthode count(). Ensuite, l'élément le plus haut de la pile est affiché à l'aide de la méthode Peek(). Ensuite, l'élément le plus haut de la pile est supprimé à l'aide de la méthode Pop(). Là encore, le nombre d'éléments et les éléments de la pile sont affichés après avoir utilisé la méthode Pop(). Ensuite, la méthode Clear() est utilisée pour supprimer tous les éléments de la pile. Là encore, le nombre d'éléments et les éléments de la pile sont affichés après avoir utilisé la méthode Clear(). La sortie du programme est affichée dans l'instantané ci-dessus.

  • Clone(): A shallow copy of the stack is created using the Clone() method.
  • Equals(Object): The Equals(Object) method is used to determine if the object specified as the parameter is equal to the current object.
  • Synchronized(Stack): A synchronized wrapper for the stack is returned using the Synchronized(Stack) method.
  • CopyTo(Array,Int32): The stack is copied into an array which is one dimensional with the index of the array specified as a parameter.
  • ToArray(): The stack is copied to a new array using ToArray() method.
  • GetType(): The type of the current instance is obtained using GetType() method.
  • ToString(): A string representing the current object is returned using ToString() method.
  • GetEnumerator(): An IEnumerator for the stack is returned using GetEnumerator() method.
  • GetHashCode(): The GetHashCode() method is the hash function by default.
  • MemberwiseClone(): A shallow copy of the current object is created using MemberwiseClone() method.

Example #2

Consider the example program below to demonstrate Clone() method, Equals() method, Synchronized() method, CopyTo() method, ToArray() method, GetType() method and GetEnumerator() method:

Code:

using System;
using System.Collections;
//a class called program is defined
class program
{
// Main Method is called
public static void Main(string[] args)
{
// creating a new stack
Stack mystk = new Stack();
mystk.Push("India");
mystk.Push("USA");
mystk.Push("Canada");
mystk.Push("Germany");
Console.Write("The elements in the Stack are : ");
foreach(varele in mystk)
{
Console.WriteLine(ele);
}
// a clone of the newly created stack is created
Stack mystk1 = (Stack)mystk.Clone();
// the top most element of the clone of the newly created stack is removed using pop() method
mystk1.Pop();
Console.Write("The elements in the clone of the Stack after using pop() method are : ");
//the elements of the clone of the newly created stack is displayed
foreach(Object ob in mystk1)
Console.WriteLine(ob);
//checking if the elements of the clone of the newly created stack and the newly created stack are equal or not
Console.Write("The elements in the clone of the Stack and the stack are equal or not : ");
Console.WriteLine(mystk.Equals(mystk1));
//Checking if the clone of the newly created stack and the newly created stack is synchronised or not
Console.WriteLine("The Clone of the newly created stack is {0}.", mystk1.IsSynchronized ? "Synchronized" : "Not Synchronized");
Console.WriteLine("The newly created stack is {0}.", mystk.IsSynchronized ? "Synchronized" : "Not Synchronized");
//a new array of strings is created and the newly created stack is assigned to this array
string[] arra = new string[mystk.Count];
// The elements of the newly created stack is copied to the array
mystk.CopyTo(arra, 0);
// the elements of the array are displayed
Console.Write("The elements of the array copied from the newly created stack are : ");
foreach(string st in arra)
{
Console.WriteLine(st);
}
//converting the elements of the newly created stack to array using toarray() method
Object[] ar1 = mystk.ToArray();
Console.Write("The elements of the array copied from the newly created stack by using ToArray() method are :");
//the elements of the array are displayed
foreach(Object st1 in ar1)
{
Console.WriteLine(st1);
}
Console.WriteLine("The type of newly created stack before using "+
"ToStringMethod is: "+mystk.GetType());
Console.WriteLine("The type of newly created stack after using "+
"ToString Method is: "+mystk.ToString().GetType());
Console.Write("The elements of the newly created stack after using GetEnumerator() method are : ");
//Getenumerator() method is used to obtain the enumerator of thestack
IEnumeratorenume = mystk.GetEnumerator();
while (enume.MoveNext())
{
Console.WriteLine(enume.Current);
}
}
}

Output:

Pile C#

In the above program, a class called program is defined. Then the main method is called. Then a new stack is created. Then the clone of the newly created stack is created by using the clone() method. Then the topmost element of the clone of the newly created stack is removed using the pop() method. Then the elements of the clone of the newly created method are displayed. Then Equals() method is used to check if the newly created stack and the clone of the newly created stack are equal or not. Then the synchronized() method is used to check if the newly created stack and the clone of the newly created stack are synchronized or not. Then Copyto() method is used to copy the newly created stack to an array and the elements of the array are displayed. Then ToArray() method is used to copy the newly created stack to another array and then the elements of the array are displayed. Then GetType() method is used to obtain the type of the newly created stack. Then ToString() method is used to convert the type stack to string. Then GetEnumerator() method is used to obtain the IEnumerator of the stack. The output of the program is shown in the snapshot above.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Article précédent:Métadonnées en C#Article suivant:Métadonnées en C#