NewsRhzhi | 先创资讯 | 旧版入口
rhzhi.net
网站首页 | NewsRhzhi | 先创资讯 | 操作系统 | 工具软件 | 办公软件 | 网站设计 | 组网专栏 | 平面设计 | 多 媒 体 | 程序开发 | 硬件资料 | 聊天软件
您现在的位置: 先创网 >> 程序开发 >> .NET >> 文章正文
Common ASP.NET Code Techniques (DPC&DWC Reference)--5
不详
2005-3-14文/佚名
    

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>

打印此页 投稿与建议 返回顶部
栏 目 索 引
软件应用 SOFTWARE
Win XP | NT/2003
Win2000 | DOS/Win9x
PowerPoint | Office
Excel | Word
网络软件 | 实用软件
媒体软件 | 系统软件
常用软件 | 办公软件
聊天软件 | 网络安全
新软试用 | Vista
设计在线 DESIGN
Dreamweaver | 3DMax
Photoshop | Flash
平面设计 | 网页设计
多 媒 体 | 精品画廊
精彩专区 SPECIAL
Q Q 专区 | 热门专题
组网玩网 | 程序开发
应用集锦 |

没有任何图片文章
相关文章
关于我们 - 联系方式 - 合作伙伴 - 网站大事记 - 网站地图 - 我要投稿
Copyright ©1997-2008 先创网 All Rights Reserved.
先创科技 版权所有