From: http://www.cnblogs.com/weiming/archive/2011/12/28/2304937.html
1. Optional parameters
Optional parameters are newly added in. net4. When the method of applying optional parameters is called, you can add the required parameters selectively, and unnecessary parameters are replaced by the default values of the parameters.
?
Class Program { /// <Summary> /// Optional parameter name parameter /// </Summary>
Static Void Main ( String [] ARGs) { Console. writeline (showcomputer ()); Console. writeline (showcomputer ( "P5300"
, "1G" )); Console. Read (); } Private Static String Showcomputer ( String CPU = "I3 370 m"
, String Ram = "4G" , String Disk = "320 GB" ) { Return "My computer... \ ncpu :" + CPU + "\ Nram :" + Ram + "\ Ndisk :" + Disk + "\ N" ; } } |
CodeRunning result diagram:
2. Named Parameters
The parameter name is attached to the parameter, so that you do not have to enter the parameter in the original Parameter order when calling the method. You only need to specify the parameter name to complete the method.
?
Class Program
{ /// <Summary> /// Optional parameter name parameter /// </Summary> Static Void Main ( String [] ARGs)
{ Console. writeline (showcomputer ( "I3 370 m" , "2G" , "320 GB" )); Console. writeline (showcomputer (Disk: "320 GB" , CPU: "I3 370 m"
, Ram: "2G" )); Console. Read (); } Private Static String Showcomputer ( String CPU,
String Ram, String Disk) { Return "My computer... \ ncpu :" + CPU + "\ Nram :" + Ram + "\ Ndisk :" + Disk + "\ N"
; } } |
The output results of the preceding code are the same. The running results are as follows:
It doesn't make much sense to change the order of the parameters. We don't need to use the name parameter to change the order, so that it can be displayed only when combined with optional parameters.
?
Class Program { /// <Summary>
/// Optional parameter name parameter /// </Summary> Static Void Main ( String [] ARGs) { Console. writeline (showcomputer (RAM:
"3G" )); Console. Read (); } Private Static String Showcomputer ( String CPU = "I3 370 m"
, String Ram = "2G" , String Disk = "320 GB" ) { Return "My computer... \ ncpu :" + CPU + "\ Nram :" + Ram + "\ Ndisk :" + Disk + "\ N" ; } } |
ProgramOnly the second parameter Ram is assigned, and other parameters are default values. You should know the running result. In this way, the named parameters and optional parameters play their unique role.