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. | 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 T 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 T 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 T method to swap over two ints and two strings int a 1 b 2 Swap int ref a ref b string si Hello s2 World Swap string 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 T method causes the compiler to generate a different version of the method. Swap int is not the same method as Swap string 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 The previous exercise showed you how to create a generic class for implementing a binary tree. The Tree T class provides the Insert method for adding data items to the tree. However if you want to add a large number of items .