首页 >> XML/WebService >> 正文
Common ASP.NET Code Techniques (DPC&DWC Reference)--5
  来源:本站整理 作者:佚名 时间:2005-6-10  

Figure 2.4
Output of Listing 2.1.4 when viewed through a browser.

Adding Elements to a Queue
In Listing 2.1.4, we begin by creating an instance of the Queue class, qTasks (line 5). In line 7 through 14, we add eight new elements to qTasks using the Enqueue method. Recall that a queue supports First In, First Out ordering, so when we get ready to remove these elements, the first element to be removed will be "Wake Up", which was the first element added.

To quickly check if a particular element is an element of the queue, you can use the Contains method. Line 18 demonstrates usage of the Contains method. Note that it takes a single parameter, the element to search for, and returns True if the element is found in the queue and False otherwise.

Removing Elements from a Queue
With a Queue, you can only remove the element at the head. With such a constraint, it's no wonder that the Queue class only has a single member to remove an element: Dequeue. Dequeue not only removes the element at the head of the queue, but it also returns the element just removed.

If you attempt to remove an element from an empty Queue, the InvalidOperationException exception will be thrown and you will receive an error. Therefore, to prevent producing a runtime error in your ASP.NET page, be sure to either place the Dequeue statement in a Try ... Catch ... Finally block or ensure that the Count property is greater than zero (0) before using Dequeue. (For more information on Try ... Catch ... Finally blocks, refer to Chapter 9, "ASP.NET Error Handling." For an example of checking the Count property prior to using Dequeue, see lines 28 through 32 in Listing 2.1.4.) As with all the other collection types, you can remove all the Queue elements with a single call to the Clear method (line 36).

There might be times when you want to access the element at the head of the Queue without removing it from the Queue. This is possible via the Peek method, which returns the element at the head of the Queue without removing it. As with the Dequeue method, if you try to Peek an empty Queue, an InvalidOperationException exception will be thrown.

Iterating Through the Elements of a Queue
One way to iterate through the elements of a Queue is to simply use Dequeue to successively grab each item off the head. This approach can be seen in lines 27 through 32 in Listing 2.1.4. The major disadvantage of this approach is that, after iteration is complete, the Queue is empty!

As with every other collection type, the Queue can be iterated via a For Each ... Next loop or through the use of an enumerator. The following code snippet illustrates using the C# foreach statement to iterate through all the elements of a Queue without affecting the structure:

Queue qMyQueue = new Queue();  // Create a Queue

qMyQueue.Enqueue(5);
qMyQueue.Enqueue(62);  // Add some elements to the Queue
qMyQueue.Enqueue(-7);

// Iterate through each element of the Queue, displaying it
foreach (int i in qMyQueue)
Response.Write("Visiting Queue Element with Value: " + i + "<br>");
Working with the Stack Class
A stack is a data structure similar to a queue in that it supports only sequential access. However, a stack does bear one major difference from a queue: Rather than storing elements with a First In, First Out (FIFO) semantic, a stack uses Last In, First Out (LIFO). A crowded elevator behaves similar to a stack: The first person who enters the crowded elevator is the last person to leave, whereas the last person to board the elevator is the first out when it reaches its destination.

Adding, Removing, and Accessing Elements in a Stack
The .NET Framework provides an implementation of the stack data type with the Stack class. A stack has two basic operations: adding an element to the top of the stack, which is accomplished with the Push method, and removing an element from the top of the stack, accomplished via the Pop method. Similar to the Queue class, the Stack class also contains a Peek method to permit developers to access the top of the stack without removing the element.

Up until this point, the code provided in the previous listings has just given you a feel for the syntax of the various collections. Listing 2.1.5, however, contains a handy little piece of reusable code that can be placed on each page of your Web site to provide a set of navigation history links for your visitors.

The code in Listing 2.1.5 uses a session-level Stack class instance that is used to store the links that a Web visitor has traversed on your site since the start of his session. Each time a user visits a Web page, the stack is displayed in a history label and the page's URL is pushed onto the stack. As the user visits various pages on your Web site, his navigation history stack will continue to grow and he will be able to quickly jump back to previous pages on your site. Basically, this is mimicking the functionality of a browser's Back button. The output is shown in Figure 2.5.

Listing 2.1.5 A Stack Is Ideal for Keeping Track of a User's Navigation History
1: <script language="c#" runat="server">
2:
3:  void Page_Load(Object sender, EventArgs e)
4:  {
5:   // See if we have a stack created or not:
6:   if (Session["History"] == null)
7:   {
8:    // the history stack has not been created, so create it now.
9:    Session["History"] = new Stack();
10:   } else {
11:    // we already have a history stack. Display the history:
12:    IEnumerator enumHistory =
13:        ((Stack) Session["History"]).GetEnumerator();
14:    while (enumHistory.MoveNext())
15:     lblStackHistory.Text += "<a href=\"" + enumHistory.Current +
16:                 "\">" + enumHistory.Current +
17:                 "</a><br>";
18:   }
19:
20:   // Push current URL onto Stack IF it is not already on the top
21:   if (((Stack) Session["History"]).Count > 0)
22:   {
23:    if(((Stack) Session["History"]).Peek().ToString() !=
24:                   Request.Url.PathAndQuery.ToString())
25:     ((Stack) Session["History"]).Push(Request.Url.PathAndQuery);
26:   } else
27:    ((Stack) Session["History"]).Push(Request.Url.PathAndQuery);
28:  }
29:
30: </script>
31:
32: <html>
33: <body>
34:   <b>Session History</b><br>
35:   <asp:label runat=server id="lblStackHistory" /><br>
36:
37:   <a href="ClearStackHistory.CSharp.aspx">Clear Stack History</a><br>
38:   <a href="Back.CSharp.aspx">Back</a>
39:
40:   <p>
41:   <b>Links:</b><br>
42:   <li><a href="Listing2.1.5.aspx">Listing2.1.5.aspx</a><br>
43:   <li><a href="Listing2.1.5.b.aspx">Listing2.1.5.b.aspx</a><br>
44: </body>
45: </html>


上一篇:Common ASP.NET Code Techniques (DPC&DWC Reference)--6 下一篇:如何在DataGrid控件中隐藏列

本篇新闻:Common ASP.NET Code Techniques (DPC&DWC Reference)--5

相关新闻
相关评论
 
评论表单加载中...
 
XML/WebService文章

 在Visual C++应

 编辑:admin

 时间:2008-3-10


   编程入门网-介绍.NET中的委派(Delegates)之三
   编程入门网-介绍.NET中的委派(Delegates)之二
   编程入门网-介绍.NET中的委派(Delegates)之一
   编程入门网-用Visual C#实现文件下载功能
   编程入门网-用C#写简单的CGI程式
最新文章
   编程入门网-介绍.NET中的委派(Delegates)之三
   编程入门网-介绍.NET中的委派(Delegates)之二
   编程入门网-介绍.NET中的委派(Delegates)之一
   编程入门网-用Visual C#实现文件下载功能
   编程入门网-用C#写简单的CGI程式
总站搜索
搜索
 
热门文章
   oracle数据库文件中的导入\导出
   用Oracle10g列值掩码技术隐藏敏感数据
   VB程序中用ADO对象动态创建数据库和表-VB.NET
   用VB6写简单程序 让电骡自动关机-VB.NET
   使用.NET2.0编写COM组件供VB调用-VB.NET
   VB.NET:键盘控制焦点移动-VB.NET
   用VB.NET绘制GDI图形-VB.NET
   vb.net中应用 ArrayList 实例-VB.NET
 
推荐文章
ASP.NET中的状态管理-ASP.NET
VC、IE、ASP环境下打印、预备的完美解决方案
oracle数据库文件中的导入\导出
VB.NET中快速访问注册表技巧-VB.NET
在vb中实现超连接的方法!和直接发邮件-VB.NET
用VB做realplayer播放列表-VB.NET
在VB.NET中如何实现和利用SortedLists-VB.NET
利用VB.NET Stopwatch对象记录时间-VB.NET
成都古羌科技有限公司版权所有: Copyright@2007-2010 ,ALL Rights Reserved 蜀ICP备07017240号