Danh mục

Creating a Generic Method

Số trang: 4      Loại file: pdf      Dung lượng: 21.37 KB      Lượt xem: 4      Lượt tải: 0    
10.10.2023

Hỗ trợ phí lưu trữ khi tải xuống: 3,000 VND Tải xuống file đầy đủ (4 trang) 0

Báo xấu

Xem trước 2 trang đầu tiên của tài liệu này:

Thông tin tài liệu:

Tạo ra một phương pháp chung Cũng như các lớp học định nghĩa chung chung, bạn cũng có thể sử dụng NET Framework. Để tạo ra phương pháp chung chung. Một phương pháp chung cho phép bạn chỉ định các tham số và kiểu trả về bằng cách sử dụng một tham số loại một cách tương tự như được sử dụng khi xác định một lớp học chung chung.
Nội dung trích xuất từ tài liệu:
Creating a Generic Method Creating a Generic MethodAs well as defining generic classes, you can also use the .NET Framework to creategeneric methods.A generic method allows you to specify parameters and return type by using a typeparameter in a manner similar to that used when defining a generic class. In this way, youcan define generalized methods that are typesafe, and avoid the overhead of casting (andboxing in some cases). Generic methods are frequently used in conjunction with genericclasses—you need them for methods that take a generic class as a parameter, or that havea return type that is a generic class.You define generic methods by using the same type parameter syntax that you use whencreating generic classes (you can also specify constraints). For example, the genericSwap method shown below can be used to swap the values in its parameters. As thisfunctionality is useful regardless of the type of data being swapped, it is helpful to defineit as a generic method:static void Swap( ref T first, ref T second){ T temp = first; first = second; second = temp;}You invoke the method by specifying the appropriate type for its type parameter. Thefollowing examples show how to use the Swap method to swap over two ints, andtwo strings:int a = 1, b = 2;Swap(ref a, ref b);...string s1 = Hello, s2 = World;Swap(ref s1, ref s2);NOTEJust as instantiating a generic class with different type parameters causes the compiler togenerate different types, each distinct use of the Swap method causes the compiler togenerate a different version of the method. Swap is not the same method asSwap; both methods just happen to have been generated from the same genericmethod and so exhibit the same behavior, albeit over different types.Defining a Generic Method to Build a Binary TreeThe previous exercise showed you how to create a generic class for implementing abinary tree. The Tree class provides the Insert method for adding data items to thetree. However, if you want to add a large number of items, repeated calls to the Insertmethod are not very convenient. In the following exercise, you will define a genericmethod called BuildTree that allows you to create a new binary tree from a list of dataitems. You will test this method by using it to construct a tree of characters.Write the BuildTree method 1. Using Visual Studio 2005, create a new project by using the Console Application template. In the New Project dialog box, name the project BuildTree and set the Location to \Microsoft Press\Visual CSharp Step By Step\Chapter 17. Select Create a new Solution from the Solution dropdown. 2. On the Project menu, click Add Reference. In the Add Reference dialog box click the Browse tab. Navigate to the folder \Microsoft Press\Visual CSharp Step By Step\Chapter 17\BinaryTree\bin\Debug, click BinaryTree.dll, and then click OK. The BinaryTree assembly will be added to the list of references shown in the Solution Explorer. 3. In the Code and Text Editor window, add the following using directive to the top of the Program.cs file: using BinaryTree; This namespace contains the Tree class. 4. Add a method called BuildTree method to the Program class. This should be a static method that takes a params array of T elements called data, and returns a Tree object. The method definition should look like this: static Tree BuildTree(params T[] data) { } NOTE The params keyword was described in detail in Chapter 11, “Understanding Parameter Arrays.” 5. The T type used for building the binary tree must implement the IComparable interface. Modify the definition of the BuildTree method and add the appropriate where clause. The updated definition of the method should look like this: static Tree BuildTree(params T[] data) where T : IComparable { } 6. Add the statements shown below to the BuildTree method. These statements instantiate a new Tree object by using the appropriate type parameter, and then iterate through the params list, adding each item to the tree by using the Insert method. The tree is passed back as the return value: static Tree BuildTree(params T[] data) where T : IComparable { Tree sortTree = new Tree (data[0]); for (int i = 1; i < data.Length; i++) { sortTree.Insert(data[i]); } return sortTree; }Test the BuildTree method 1. In the Main method of the Program class, add the following statements that create a new Tree for holding character data, populates it with some sample data by using the BuildTree method, and then displays it by using the WalkTree method of the Tree: 2. Tree charTree = BuildTree(Z, X, A, M, Z, M, N); charTree.WalkTree(); 3. On the Build menu, click Build Solution. Verify that the solution compiles, correcting any errors if necessary. 4. On the Debug menu, click Start Without Debugging. When the program runs, the character values will be displayed, in order: A, M, M, N, X, Z, Z 5. Press the Enter key to return to Visual Studio 2005. • If you want to continue to the next chapter Keep Visual Studio 2005 running and turn to Chapter 18.• If you want to exit Visual Studio 2005 now On the File menu, click Exit. If you see a Save dialog box, click Yes.

Tài liệu được xem nhiều: