Before C #4.0, to call a method, you must strictly follow the number, type, or even parameter sequence and method. But this problem can be solved in C #4.0. 1. optional parameter. It can be understood as two situations: ① if a parameter is not specified, a default value is given. ② If the parameter value is specified, the default value is not used. In this way, you do not need to judge every time or write a heavy-load function. CodeAs follows:
Class Program { Static Void Main ( String [] ARGs) {program Program =New Program (); Int M = program. Add ( 10 ); // Here M = 11; default B = 1; Int N = program. Add ( 10 , 20 ); // Here n = 30; Where B = 20; } Public Int Add ( Int A, Int B = 1 ){ Return A + B; // If the value of B is not specified when a function is called, the default value is 1; }}
2. Name Parameters Optional parameters solve the default value of parameters, while named parameters solve the order of parameters. We generally determine the order of parameters when a method is called according to the parameter sequence when the method is defined, for example:
Class Program { Static Void Main ( String [] ARGs) {program Program = New Program (); Int M = 5 ; Int N = 30 ; Int Result = program. getlastnum (Y: n, x: m ); // Note. The interchange between the positions of X and Y. // Not in the order required by the Method } Public Int Getlastnum ( Int X, Int Y ){ If (X <Y ){ Return X ;} Return 0 ;}