Let's look at one such method
Public Voidprinttest (string word) { Console.WriteLine ("{0}", word); Console.readkey (); }
This method can only print out word included characters If you want to print out the word contains the characters out of the adjustment, Then modify the word variable. What's the best way for us to control the number of parameters at random when invoking a method? See params
Look at the optimized Printtest method:
public void Printtest (params string[]words) { string word= "start" +strpersonal; if (words! = null) {for (int i = 0; I <words. Count (); i++) { Word = Word + "," + words[i]; } } Console.WriteLine ("{0}", word); Console.readkey (); }
When invoking a method, write as:
Mytest.printtest ("Hum"); --Output: Hum mytest.printtest ("Hum", "ha");--Output: Hum, ha mytest.printtest ("Hum", "ha", "Hum Ha");--Output: Hum, ha, hum.
You can also write this:
String[]words = new string[] {"Hum", "ha", "Hum"}; Mytest.printtest (words); --Output: Hum, ha, hum
in General, the number of parameters is fixed. NET provides a more flexible mechanism for implementing variable number parameters, which is to use the params modifier. The advantage of a variable number parameter is that in some cases it is easy to implement an indeterminate number of parameters, such as calculating the weighted sum of arbitrary numbers, linking arbitrary strings to a string, and so on.
when using params , you should also pay attention to some places,
1. The params modified parameter must be a one-dimensional array.
2, params modified parameter array, can be any type, as long as the array type is set to object.
3. The params must be the last one in the parameter list and can only be used once.
. NET Basic Literacy-params