Queue隊列就是先進先出。它並無實現 IList,ICollection。因此它不能按索引訪問元素,不能使用Add和Remove。下面是 Queue的一些方法和屬性html
Enqueue():在隊列的末端添加元素數組
Dequeue():在隊列的頭部讀取和刪除一個元素,注意,這裏讀取元素的同時也刪除了這個元素。若是隊列中再也不有任何元素。就拋出異常ide
Peek():在隊列的頭讀取一個元素,可是不刪除它ui
Count:返回隊列中的元素個數this
TrimExcess():從新設置隊列的容量,由於調用Dequeue方法讀取刪除元素後不會從新設置隊列的容量。spa
Contains():肯定某個元素是否在隊列中3d
CopyTo():把元素隊列複製到一個已有的數組中code
ToArray():返回一個包含元素的新數組orm
作一個小例子來講明下隊列的用法:htm
首先創建一個實體類
[Serializable] public class Person:IEquatable<Person> { private string name; public string Name { get { return name; } set { name = value; } } private string phone; public string Phone { get { return phone; } set { phone = value; } } private bool? isGet; public bool? IsGet { get { return isGet; } set { isGet = value; } } public Person() { } public Person(string name, string phone,bool? isGet) { this.name = name; this.phone = phone; this.isGet = isGet; } public bool Equals(Person person) { if (person == null) { return false; } if (this.name == person.name && this.phone == person.phone) { return true; } else { return false; } } }
而後創建一個queue的包裝類
public class Manager { private Queue<Person> queue = new Queue<Person>(); public void Add(Person p) { queue.Enqueue(p); } public Person Get() { return queue.Dequeue(); } public bool IsGet(Person p) { bool resule = false; resule = queue.Contains(p); return resule; } public bool IsHaveElement() { if (queue.Count <= 0) { return false; } else { return true; } } public int GetQueueCount() { return queue.Count; } }
剩下就是搞一個winform界面:
最後,就能夠向隊列里加東西了,每次顯示的時候 都從隊列裏減一條
public partial class Form1 : Form { private Manager manager; public Form1() { manager=new Manager(); InitializeComponent(); } private void btnSelect_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtPhone.Text.Trim()) || string.IsNullOrEmpty(txtPhone.Text.Trim())) { MessageBox.Show("Invalided Message"); } else { string name = txtName.Text.Trim(); string phone = txtPhone.Text.Trim(); if (manager.IsGet(new Person(name, phone, null))) { MessageBox.Show("This list have already in queue"); } else { manager.Add(new Person(name, phone, null)); txtName.Text = string.Empty; txtPhone.Text = string.Empty; tsLabel.Text ="Number : "+ manager.GetQueueCount().ToString(); // MessageBox.Show("OK!"); } } } private void btnView_Click(object sender, EventArgs e) { Person person = new Person(); if(manager.IsHaveElement()) { person = manager.Get(); ListViewItem li = new ListViewItem(); li.SubItems[0].Text = person.Name; li.SubItems.Add(person.Phone); listView.Items.Add(li); tsLabel.Text = "Number : " + manager.GetQueueCount().ToString(); } else { MessageBox.Show("No user"); } } }
可見如下運行結果,其中狀態欄中的Number是指隊列中元素的數量
轉載:http://www.cnblogs.com/xuekai-to-sharp/p/3540709.html?utm_source=tuicool&utm_medium=referral