tailieunhanh - Suppose Minimum Value
Using Array Arguments Suppose you want to write a method to determine the minimum value in a set of parameters. One way would be to use an array. | Using Array Arguments Suppose you want to write a method to determine the minimum value in a set of parameters. One way would be to use an array. For example to find the smallest of several int values you could write a static method called Min with a single parameter representing an array of int values class Util public static int Min int paramList if paramList null 0 throw new ArgumentException int currentMin paramList 0 foreach int i in paramList if i currentMin currentMin i return currentMin To use the Min method to find the minimum of two int values you would write this int array new int 2 array 0 first array 1 second int min array And to use the Min method to find the minimum of three int values you would write this int array new int 3 array 0 first array 1 second array 2 third int min array You can see that this solution avoids the need for a large number of overloads but it does so at a price You have to write additional code to populate the array passed in. However you can get the compiler to write some of this code for you by using the params keyword to declare a params array. Declaring params Arrays You use the params keyword as an array parameter modifier. For example here s Min again this time with its array parameter declared as a params array class Util public static int Min params int paramList code exactly as before The effect of the params keyword on the Min method is that it allows you to call it by using any number of integer arguments. For example to find the minimum of two integer values you would write this int min first second The compiler translates this call into code similar to this int array new int 2 array 0 first array 1 second int min array To find the minimum of three integer values you would write the code shown below which is also converted by the compiler into the corresponding code that uses an array int min first second third Both calls to Min one call with .
đang nạp các trang xem trước