C#内置队列类Queue用法实例
本文实例讲述了C#内置队列类Queue用法。分享给大家供大家参考。具体分析如下:
这里详细演示了C#内置的队列如何进行添加,移除等功能。
usingSystem; usingSystem.Collections.Generic; classExample { publicstaticvoidMain() { Queue<string>numbers=newQueue<string>(); numbers.Enqueue("one"); numbers.Enqueue("two"); numbers.Enqueue("three"); numbers.Enqueue("four"); numbers.Enqueue("five"); //Aqueuecanbeenumeratedwithoutdisturbingitscontents. foreach(stringnumberinnumbers) { Console.WriteLine(number); } Console.WriteLine("\nDequeuing'{0}'",numbers.Dequeue()); Console.WriteLine("Peekatnextitemtodequeue:{0}", numbers.Peek()); Console.WriteLine("Dequeuing'{0}'",numbers.Dequeue()); //Createacopyofthequeue,usingtheToArraymethodandthe //constructorthatacceptsanIEnumerable<T>. Queue<string>queueCopy=newQueue<string>(numbers.ToArray()); Console.WriteLine("\nContentsofthefirstcopy:"); foreach(stringnumberinqueueCopy) { Console.WriteLine(number); } //Createanarraytwicethesizeofthequeueandcopythe //elementsofthequeue,startingatthemiddleofthe //array. string[]array2=newstring[numbers.Count*2]; numbers.CopyTo(array2,numbers.Count); //Createasecondqueue,usingtheconstructorthatacceptsan //IEnumerable(OfT). Queue<string>queueCopy2=newQueue<string>(array2); Console.WriteLine("\nContentsofthesecondcopy,withduplicatesandnulls:"); foreach(stringnumberinqueueCopy2) { Console.WriteLine(number); } Console.WriteLine("\nqueueCopy.Contains(\"four\")={0}", queueCopy.Contains("four")); Console.WriteLine("\nqueueCopy.Clear()"); queueCopy.Clear(); Console.WriteLine("\nqueueCopy.Count={0}",queueCopy.Count); } } /*Thiscodeexampleproducesthefollowingoutput: one two three four five Dequeuing'one' Peekatnextitemtodequeue:two Dequeuing'two' Contentsofthecopy: three four five Contentsofthesecondcopy,withduplicatesandnulls: three four five queueCopy.Contains("four")=True queueCopy.Clear() queueCopy.Count=0 */
希望本文所述对大家的C#程序设计有所帮助。