intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

Creating a Generic Method

Chia sẻ: Nghia Tuan | Ngày: | Loại File: PDF | Số trang:4

74
lượt xem
5
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

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.

Chủ đề:
Lưu

Nội dung Text: Creating a Generic Method

  1. Creating a Generic Method As well as defining generic classes, you can also use the .NET Framework to create generic methods. A generic method allows you to specify parameters and return type by using a type parameter in a manner similar to that used when defining a generic class. In this way, you can define generalized methods that are typesafe, and avoid the overhead of casting (and boxing in some cases). Generic methods are frequently used in conjunction with generic classes—you need them for methods that take a generic class as a parameter, or that have a return type that is a generic class. You define generic methods by using the same type parameter syntax that you use when creating generic classes (you can also specify constraints). For example, the generic Swap method shown below can be used to swap the values in its parameters. As this functionality is useful regardless of the type of data being swapped, it is helpful to define it 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. The following examples show how to use the Swap method to swap over two ints, and two strings: int a = 1, b = 2; Swap(ref a, ref b); ... string s1 = "Hello", s2 = "World"; Swap(ref s1, ref s2); NOTE Just as instantiating a generic class with different type parameters causes the compiler to generate different types, each distinct use of the Swap method causes the compiler to generate a different version of the method. Swap is not the same method as Swap; both methods just happen to have been generated from the same generic method and so exhibit the same behavior, albeit over different types. Defining a Generic Method to Build a Binary Tree
  2. The previous exercise showed you how to create a generic class for implementing a binary tree. The Tree class provides the Insert method for adding data items to the tree. However, if you want to add a large number of items, repeated calls to the Insert method are not very convenient. In the following exercise, you will define a generic method called BuildTree that allows you to create a new binary tree from a list of data items. 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.
  3. 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.
  4. • If you want to exit Visual Studio 2005 now On the File menu, click Exit. If you see a Save dialog box, click Yes.
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2