Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
ASP .NET 2.0 Beta Preview - B. Evjen.pdf
Скачиваний:
26
Добавлен:
24.05.2014
Размер:
15.33 Mб
Скачать

Visual Basic 8.0 and C# 2.0 Language Enhancements

Iterators

Iterators enable you to specify how your classes or collections work when they are dissected in a foreach loop. The iterators are used only in C#. Visual Basic 8.0 developers do not have a similar feature at present.

You can iterate through a collection of items just as you have always been able to do in C# 1.0 because the item implements the GetEnumerator function. For example, you can just run a foreach loop over an ArrayList, as shown in Listing 15-6.

Listing 15-6: Running the foreach loop over an ArrayList

void Page_Load(object sender, EventArgs e)

{

ArrayList myList = new ArrayList();

myList.Add(“St. Louis Rams”); myList.Add(“Indianapolis Colts”); myList.Add(“Minnesota Vikings”);

foreach (string item in myList)

{

Response.Write(item.ToString() + “<br />”);

}

}

This code writes all three values that were added to the ArrayList to the browser screen. Iterators enable you to run a foreach loop on your own items such as classes. To run a foreach loop, you create a class that implements the IEnumerable interface.

The first step is to create a class in your Web solution. To create a class, create a folder in your solution and give it the name Code. Then place a new .cs class file in the Code directory. This class is illustrated in Listing 15-7.

Listing 15-7: Creating a class that works with a foreach loop

using System;

using System.Collections;

public class myList

{

internal object[] elements; internal int count;

public IEnumerator GetEnumerator()

{

yield return “St. Louis Rams”; yield return “Indianapolis Colts”; yield return “Minnesota Vikings”;

}

}

419

Chapter 15

This class, myList, imports the System.Collections namespace so that it can work with the IEnumerable interface. In its simplest form, the myList class implements the enumerator pattern with a method called GetEnumerator(), which returns a value defined as IEnumerable. Then each item in the collection is returned with the yield return command. The yield keyword in C# is used to provide a value to the enumerator object or to signal the end of the iteration.

Now that the class myList is in place, you can then instantiate the class and iterate through the class collection using the foreach loop. This is illustrated in Listing 15-8.

Listing 15-8: Iterating though the myList class

void Page_Load(object sender, EventArgs e)

{

myList IteratorList = new myList();

foreach (string item in IteratorList)

{

Response.Write(item.ToString() + “<br />”);

}

}

This ASP.NET Page_Load event simply creates an instance of the myList collection and iterates through the collection using a foreach loop. This is all possible because an IEnumerable interface was implemented in the myList class. When you run this page, each of the items returned from the myList class using the yield return command displays in the browser.

One interesting change you can make in the custom myList class is to use the new generics capabilities provided by C#. Because you know that only string types are being returned from the myList collection, you can define that type immediately to avoid the boxing and unboxing that occurs using the present construction. Listing 15-9 shows the changes you can make to the class that was first presented in Listing 15-7.

Listing 15-9: Creating a class that works with a foreach loop using generics

using System;

using System.Collections;

using System.Collections.Generic;

public class myList : IEnumerable<string>

{

internal object[] elements; internal int count;

public IEnumerator<string> GetEnumerator()

{

yield return “St. Louis Rams”; yield return “Indianapolis Colts”; yield return “Minnesota Vikings”;

}

}

420

Visual Basic 8.0 and C# 2.0 Language Enhancements

Anonymous Methods

Anonymous methods enable you to put programming steps within a delegate that you can later execute instead of creating an entirely new method. This can be handled in a couple different ways. You should note that anonymous methods are only available in C# and are not present in Visual Basic 8.0.

Without using anonymous methods, create a delegate that is referencing a method found elsewhere in the class file. In the example from Listing 15-10, when the delegate is referenced (by a button-click event), the delegate invokes the method that it points to.

Listing 15-10: Using delegates in a traditional manner

public partial class Default_aspx

{

void Page_Load(object sender, EventArgs e)

{

this.Button1.Click += ButtonWork;

}

void ButtonWork(object sender, EventArgs e)

{

Label1.Text = “Welcome to the camp, I guess you all know why you’re here.”;

}

}

In the example in Listing 15-10, you see a method in place called ButtonWork, which is only called by the delegate in the Page_Load event. Anonymous methods now enable you to avoid creating a separate method and allow you to place the method directly in the delegate declaration instead. An example of the use of anonymous methods is shown in Listing 15-11.

Listing 15-11: Using delegates with an anonymous method

public partial class Default_aspx

{

void Page_Load(object sender, EventArgs e)

{

this.Button1.Click += delegate(object myDelSender, EventArgs myDelEventArgs)

{

Label1.Text = “Welcome to the camp, I guess you all know why you’re here.”;

};

}

}

Using anonymous methods, you don’t create a separate method. Instead you place necessary code directly after the delegate declaration. The statements and steps to be executed by the delegate are placed between curly braces and closed with a semicolon.

421

Chapter 15

Operator Overloading

Operator overloading enables you to define the +, , *, / and other operators in your classes just as the system classes can. This is a feature that has always been present in C#, but is now available in Visual Basic 8.0 as well. It gives you the capability to provide the objects in your classes with a similar feel when used with operators as if they were simply of type String or Integer.

Giving your classes this extended capability is a matter of simply creating a new method using the Operator keyword followed by the operator that you want to overload. An example of the Operator functions is illustrated in Listing 15-12.

Listing 15-12: Example operator overloading functions

Public Shared Operator +(ByVal Left As Point, ByVal Right As Size) As Point Return New Point(Left.X + Right.Width, Left.Y + Right.Height)

End Operator

Public Shared Operator -(ByVal Left As Point, ByVal Right As Size) As Point Return New Point(Left.X – Right.Width, Left.Y – Right.Height)

End Operator

Two different types of operators can be overloaded from Visual Basic — unary and binary operators:

Overloadable unary operators include: + – Not IsTrue IsFalse Widening Narrowing

Overloadable binary operators include: + – * / \ & Like Mod And Or Xor ^ <<

>> = <> > < >= <=

Par tial Classes

Partial classes are a new feature included with the .NET Framework 2.0 and available to both C# and Visual Basic 8.0. These classes allow you to divide up a single class into multiple class files, which are later combined into a single class when compiled.

Partial classes are the secret of how ASP.NET keeps the new code-behind model simple. In ASP.NET 1.0/1.1, the code-behind model included quite a bit of code labeled as machine-generated code (code generated by the designer) and hidden within #REGION tags. Now, however, the code-behind file for ASP.NET 2.0 looks rather simple. A sample of the new code-behind model that uses partial classes is shown in Listing 15-13.

Listing 15-13: The new code-behind model using partial classes

VB

Imports Microsoft.VisualBasic

Namespace ASP

Partial Class Default_aspx

422

Visual Basic 8.0 and C# 2.0 Language Enhancements

Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Label1.Text = “Hello “ & Textbox1.Text

End Sub

End Class

End Namespace

C#

using System;

namespace ASP {

public partial class Default_aspx

{

void Button1_Click (object sender, System.EventArgs e)

{

Label1.Text = “Hello “ + Textbox1.Text;

}

}

}

This code-behind file contains a simple button-click event and nothing else. If you compare it to the designer code (as it was called) from the code-behind files found in ASP.NET 1.0/1.1, you notice a big difference between the two. What happened to all that code in the original code-behind file? It is still there, but now with the use of partial classes, all that necessary (but untouchable) code is kept in a separate class file. Upon compilation, the class file shown in Listing 15-14 is merged with the other class file. The result shows you that the code-behind files in ASP.NET 2.0 can consist simply of objects that you actually work with.

Partial classes are created with the use of the Partial keyword in Visual Basic and with the partial keyword in C# for any classes that are to be joined with a different class. The Partial keyword precedes the Class keyword for the classes to be combined with the original class. Besides using partial classes with every code-behind page that you work with in ASP.NET 2.0, you can also employ the same techniques with your own class files. You can associate two or more classes as part of the same class by using the procedure shown in Listings 15-14 and 15-15.

Listing 15-14: The first class

VB

Public Class Calculator

Public Function Add(ByVal a As Integer, ByVal b As Integer)

Return (a + b)

End Function

End Class

(continued)

423

Chapter 15

Listing 15-14: (continued)

C#

public class Calculator

{

public int Add(int a, int b)

{

return a + b;

}

}

Listing 15-15: The second class

VB

Partial Class Calculator

Public Function Subtract(ByVal a As Integer, ByVal b As Integer)

Return (a - b)

End Function

End Class

C#

public partial class Calculator

{

public int Subtract(int a, int b)

{

return a - b;

}

}

When the two separate files are compiled, the two class files appear as a single object. The first class shown in Listing 15-15 is constructed just as a normal class is, whereas any additional classes that are to be made a part of this original class use the new Partial keyword. A consumer using the compiled Calculator class will see no difference. After the consumer of the Calculator class creates an instance of this class, this single instance has both an Add and a Subtract method to it. This is illustrated in Figure 15-1.

424