C#中queue的用法


  Queue隊列就是先進先出。它並沒有實現 IList,ICollection。所以它不能按索引訪問元素,不能使用Add和Remove。下面是 Queue的一些方法和屬性

  Enqueue():在隊列的末端添加元素

  Dequeue():在隊列的頭部讀取和刪除一個元素,注意,這里讀取元素的同時也刪除了這個元素。如果隊列中不再有任何元素。就拋出異常

  Peek():在隊列的頭讀取一個元素,但是不刪除它

  Count:返回隊列中的元素個數

  TrimExcess():重新設置隊列的容量,因為調用Dequeue方法讀取刪除元素后不會重新設置隊列的容量。

  Contains():確定某個元素是否在隊列中

  CopyTo():把元素隊列復制到一個已有的數組中

  ToArray():返回一個包含元素的新數組

做一個小例子來說明下隊列的用法:

首先建立一個實體類

復制代碼
 [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是指隊列中元素的數量

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM