Chapter 4 functions in Visual C # Best Practices (II): Function Classification

Source: Internet
Author: User
ArticleDirectory
    • 4.2 function category
Chapter 4 Functions

Many people are still confused about what functions and methods are. In fact, these two concepts are the same thing. Methods are the product of object-oriented. For example, we say that a method of an object is used, and functions are the product of process-oriented. For example, we often say that a function is executed. Both functions and methods are written in the same way. This chapter will introduce the related concepts of functions in detail.
The focus of this chapter:
◆ Function parameters and transmission methods
◆ Function return value

4.2 function category

This section describes the function parameters and return values. At the same time, we will introduce the transfer methods of functions: value transfer method and reference transfer method, hoping to help you.

4.2.1 function parameters and transmission methods

When defining a function, the parameters in parentheses following the function name are called formal parameters. In the following example, A and B are both form parameters.
Int sum (int A, int B)
{
...... // Statement body
}
The following parameter definitions are incorrect.
Int sum (int A, B)
{
...... // Statement body
}
When you call a function, the parameters in parentheses following the function name are called actual parameters (real parameters. Real parameters can be constants, assigned variables, or expressions. The Order, type, and number of real parameters must be consistent with those in the corresponding parameter table. In the following example, both A and B are real parameters.
Int A = 10;
Int B = 100;
Int result = sum (A, B );
For real parameters, the system not only specifies its type in the called function, but also allocates storage units for it. When defining a parameter, it only specifies its type and does not allocate storage units for them in memory. A temporary storage unit identifier is assigned to a parameter only when it is called. After the function is executed, it is returned to call the function, and the storage unit identifier is immediately revoked.
In C # language, there are two ways to pass the form between real parameters.
1. Value Transfer Method
When using this method, call a function to pass the value of the real parameter (constant, variable, or computable expression) to the Temporary Variable storage unit set by the called function parameter, the change of the called function parameter value does not affect the real parameters of the called function. After the call is complete, the storage unit of the form parameter is released, and the real parameter remains unchanged. This method can only transmit data from the real parameter to the shape parameter, that is, one-way transmission.
Here is an example:
Using system;
Namespace Microsoft. Example
{
Public class testvaluetransfer
{
Static int power (int I, int N) // defines a cubic function.
{
Int result = I; // defines an int variable.
For (Int J = 0; j <n-1; j ++)
{
Result = Result * I; // implement the cubic Logic
}
Return result; // return result
}
Static void main (string [] ARGs)
{
Int I = 20; // defines an int variable.
Console. writeline ("before passing a value, the I value is:" + I );
Int result = power (20, 3); // call a cubic function
Console. writeline ("after the value is passed, the value of I is:" + I );
Console. writeline ("the result after I Power 3 is:" + result );
}
}
}
Above Code In, the initial value of variable I in row 8th is 20. The parameter is passed to call Cube The called function power (). When running the called function, the copy value of the real parameter is passed to the Temporary Variable storage unit I in the called function. The value is 8000. The change of the called function parameter value does not affect the real parameters of the called function. After the call, the storage unit I of the called function is released, and the real parameter I remains unchanged, that is, I = 20.
The final output result is:
Before passing a value, the I value is 20.
After the value is passed, the value of I is 20.
The result after I Power 3 is: 8000
2. Reference Transfer Method
In a value transfer call, the value of the form parameter cannot be returned to the real parameter. However, in actual use, two-way transmission is required. For this purpose, reference transmission is usually used.
When the real parameter is an array name or an object name, the real parameter is the address passed to the form parameter. If the real parameter is an array name, the call function will pass the starting address of the real parameter array to the temporary variable unit of the called function parameter, instead of passing the value of the real parameter array element. In this case, the corresponding form parameter can be the name of the form parameter array. In this transfer method, when a function is called for execution, the starting address and subscript increment of the real parameter array passed by the real parameter are used to directly access the corresponding array elements, therefore, the change in the parameter value is actually a change in the element value of the array of real parameters that call the function.
If the real parameter is an object name, call the function to pass the address of the Unit pointed to by the real parameter object to the Temporary Variable storage unit of the called function parameter. In this case, the corresponding parameters must be of the same object type. When the called function is executed, it also directly accesses the corresponding unit. The change of the form parameter directly changes the corresponding unit of the called function parameter.
Therefore, when the real parameter is an array name or an object name, the passing of the real parameter is bidirectional transfer, which is called "Address Transfer ".
(1) Representation of array names as function parameters
When the array name is used as a function parameter, you also need to describe its type. For example, you can write it as follows:
NT [] values = new int [20];
Test (values );
Here is an example:
Sing system;
Namespace Microsoft. Example
{
Public class testrefertransfer
{
Static void double (INT [] values) // defines the 2-fold Function
{
For (INT I = 0; I <values. length; I ++)
{
Values [I] = values [I] * 2; // implement 2x Logic
}
}
Static void main (string [] ARGs)
{
Int [] values = {1, 2, 3}; // defines an array of the int type.
Console. writeline ("before the reference is passed, the value of values is :");
For (INT I = 0; I <values. length; I ++)
{
Console. Write (Values [I] + ""); // output the value of values before the function is called.
}
Double (values); // call the Double Function
Console. writeline ();
Console. writeline ("after the reference is passed, the value of values is :");
For (INT I = 0; I <values. length; I ++)
{
Console. Write (Values [I] + ""); // output the values value after the function is called.
}
Console. writeline ();
}
}
}
In the above Code, the values variable of the second row is an array. It is passed by referencing the parameter and calls the double function to multiply all elements in the array by 2. When the called function is run, the reference address of the array is passed to the value of the Temporary Variable storage unit values in the called function. The change of the called function parameter value has an impact on the real parameters of the called function. After the call is completed, all the elements in the values array of the first row are changed.
The final output result is:
Before the reference is passed, the value of values is:
1 2 3
After the reference is passed, the value of values is:
2 4 6
Author's experience:
Note: When using an array name as a function parameter, you must define an array in the called function and called function respectively. The type of the parameter array must be the same as that of the real parameter array. Otherwise, an error occurs. When using arrays as function parameters, initialization must be performed first. Otherwise, compilation fails.
In addition, values is defined as a one-dimensional integer array with three elements. To improve the versatility of functions, the length of the array is not specified when the parameter array is described, but only the type, array name, and each other square brackets are given, this allows the same function to process arrays of different lengths as needed.
(2) In order Program To understand the actual length of the currently processed array, we often need to use another keyword Param.
Here is an example:
Using system;
Namespace Microsoft. Example
{
Public class testparamtransfer
{
Static void double (Params int [] values) // defines the 2-fold Function
{
For (INT I = 0; I <values. length; I ++)
{
Values [I] = values [I] * 2; // implement 2x Logic
Console. Write (Values [I] + ""); // output result
}
}
Static void main (string [] ARGs)
{
Double (1, 2, 3, 4, 5); // call the double function using five parameters.
Console. writeline ();
Double (1, 2, 3); // use three parameters to call the double function.
Console. writeline ();
}
}
}
In the above Code, we use five parameters in row 16th to call the double function, while row 18th uses three parameters to call the double function. This is very convenient. When talking about arrays, we know that arrays must be initialized before they can be used. Once the initialization size is fixed, and the array size cannot be modified, this will bring us a lot of inconvenience. After the Params keyword is used, we can bring greater convenience to our functions and make better reuse of code. We don't need to define a method with five parameters, and define another method with three parameters.
The final output result is:
2 4 6 8 10
2 4 6

4.2.2 return value of the Function

The purpose of a function call is generally to obtain a computing result or execute an operation. In order to get a result, this is easy to understand. If you need to get the result, you must have a local return value. Therefore, operations are easy to ignore. For example, if we need to delete a file, we need to tell the caller whether the operation is successful or not. This also requires the return value.
The return statement can be used to return the calculation result (that is, the return value) to the call function. At the same time, the execution flow of the program is also transferred to the next statement of the Call Statement for execution.
The returned statement format is as follows:
Return (expression );
Or return expression;
When a function returns a value, you can obtain the returned value at the place where the function is called and save it in a variable. The Return Value Type of a function must be the same as the type of the expression value in the return statement. However, the C # language can be different. In this case, the system automatically performs implicit type conversion to make it consistent.
When a function does not return a value, the type of the return value can be expressed as void, which indicates "No type" or "null type ". When a function without a return value is called, a separate call statement is usually used. Common console. wrile () functions are called in this form. Example: console. wrile ("Hello world !"); Only outputs strings on the screen without returning values.
Here is an example:
Using system;
Namespace Microsoft. Example
{
Public class testreturnvalue
{
Static int max (int x, int y) // defines the max Function
{
Int Z;
Z = x> Y? X: Y; // compare the size of X and Y.
Return Z;
}
Static void main (string [] ARGs)
{
Int X, Y, result; // defines three integer variables.
Console. writeline ("Enter X :");
Int. tryparse (console. Readline (), out X); // type conversion
Console. writeline ("Enter Y :");
Int. tryparse (console. Readline (), out y); // type conversion
Result = max (x, y); // call the max Function
Console. writeline ("the maximum number is:" + result );
}
}
}
In the above Code, line 3 defines the max function to compare the two numbers, and then return the larger value to the function call. The max function defines that the return type is int, so the ruturn value must also be Int. At the same time, the result variable used to save the return value of row 19th must also be of the int type.
The final output result is:
Enter X:
1
Enter Y:
3
The maximum number is 3.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.