Generic Method-Lesson and Extract

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 | 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 .

Bấm vào đây để xem trước nội dung
TÀI LIỆU LIÊN QUAN
5    176    1
5    255    1
5    106    0
5    121    1
6    103    1
6    107    1
6    121    1
6    103    0
6    140    0
TÀI LIỆU MỚI ĐĂNG
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.