c# queue 实例
时间: 2023-09-24 12:13:08 浏览: 59
以下是一个C#的Queue(队列)实例:
```csharp
using System;
using System.Collections;
class Program
{
static void Main()
{
Queue myQueue = new Queue();
// 添加元素到队列中
myQueue.Enqueue("Apple");
myQueue.Enqueue("Banana");
myQueue.Enqueue("Cherry");
myQueue.Enqueue("Date");
// 遍历队列
foreach (object obj in myQueue)
{
Console.WriteLine(obj);
}
// 移除队列中的元素
object firstItem = myQueue.Dequeue();
Console.WriteLine("Removed item: " + firstItem);
// 遍历队列
foreach (object obj in myQueue)
{
Console.WriteLine(obj);
}
Console.ReadLine();
}
}
```
输出结果:
```
Apple
Banana
Cherry
Date
Removed item: Apple
Banana
Cherry
Date
```
在上面的示例中,我们首先实例化一个Queue对象,并使用Enqueue()方法将一些元素添加到队列中。接下来,通过使用foreach循环,我们遍历队列中的所有元素。
然后,我们使用Dequeue()方法从队列中移除第一个元素。最后,再次遍历队列,以确保第一个元素已被移除。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)