当前位置:网站首页>C self learning function
C self learning function
2022-06-24 18:39:00 【MousseIn】
C# A function of
Preface
- This study C# Our goal is to lay a good foundation from the beginning C# Fundamentals of advanced development , Leak filling , Complete the necessary technologies for advanced development . The content of this article and my study are based on 《C# Introductory classic ( Eighth Edition )》 And what I have created with my own understanding , You are very welcome to comment and add , Thank you. , Thanks to the author and compiler of this book , Thank them for their efforts .
Define and use functions
This is the function , Some places are called " Method ". But the term is .NET Programming has a very special meaning , So we don't use this term now .
The code just seen by beginners is in the form of a single code block , It contains some lines of code that are executed repeatedly , And conditionally executing branch statements . If you want to operate on the data , It's time to put the code in the right place .
This code structure is relatively limited , In case of actual coding needs , Most of them need to put a piece of code in multiple places in the program to execute , If you do that , Even very small changes to the inserted code block ( For example, there is a code error ), You also need to modify the entire code block , So as to have a great impact , Cause the entire application to fail , And the application is relatively long .
The solution to this problem is to use the function . stay C# in , Function provides a block of code that is executed anywhere in the application .
Function can improve the readability of the code , It can also be used to create multipurpose code , Let the door perform the same operation on different data . You can pass information to functions in the form of parameters , The result of the function is obtained in the form of the returned value .
The definition of the function includes Function name 、 Return type 、 And one. parameter list , Among them the parameter list Specifies the... Required by this function The number of arguments and Parameter type . function Name and Parameters ( Not a return type ) Jointly define the function's Signature .
- See the following example :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace Ch06Ex01
{
class Program
{
static void Write()
{
WriteLine("Text output from function.");
}
static void Main(string[] args)
{
Write();
ReadKey();
}
}
}
In this case , It is the following code that defines the function Write():
static void write()
{
writeLine("Text output from function.");
}
Looking at the example above, we can conclude that : The function definition consists of the following parts :
- Two keywords :static and void
- The function name is followed by parentheses , Such as Wirte()
- A block of code to execute , In curly braces
In general, we use PascalCase Form to write the function name .
We define Write() The code for the function is very similar to other code in the application :
static void Main(string[] args)
{
...
}
This is because , All the code we've written so far ( Definition types are excluded ) Are all part of a function .
The function Main() Is the console application Entry function , After this function is executed , The application terminates . all C# Executable code must have an entry point .
but Main() function And above write() The only difference between functions ( In addition to the code they contain ) Is the function name Main There is also some code in parentheses , This is the designation Method of parameters .
Main() Functions and Write Functions use keywords static and void Defined .
void Easier to explain . This keyword indicates that the function has no return value .
The code called is as follows :
Write();
Type a function name , Just follow the parentheses .
When the program reaches this line of code , It will run Writr() Code in function .
When defining and calling functions , You must use parentheses . If you delete them , Will not compile code .
Return value
The easiest way to swap functions is to use Return value . Return value Same as variables , All have data types .
When a function returns a value , Parameters must be modified in two ways :
- Specify a return value type in the function declaration , But you can't use keywords void.
- Use return Keyword to end the execution of a function , Pass the return value to the calling code .
- When the system executes to return At the time of statement , The program will immediately Return the calling code . The code after this statement will not be executed . But it doesn't mean return Statements can only be placed on the last line of the function body .
Parameters
When a function accepts a function , The following must be specified :
- The function specifies the list of accepted parameters in the definition , And these parameter types .
- Provide a list of matching arguments in each function call .
C# The formal parameters in are part of the function definition , The arguments are passed from the calling code to the function .
But these two terms are often simply called parameters .
Parameter match
When the function is called , The supplied arguments must match the arguments specified in the function definition . This means matching the type of the parameter 、 Number and order .
Parameters of the array
C# It is allowed to specify a... For a function in ( Only one... Can be specified ) Special parameters , This parameter must be the last parameter in the function definition . Parameter arrays allow functions to be called with indefinite parameters , You can use params Keyword to call them .
Parameter arrays can simplify code , Because there is no need to pass an array in the calling code , Instead, you pass several parameters of the same type, which are placed in an array that can be used in the function .
Reference parameters and value parameters
Value parameter : When using parameters , Pass a value to a variable used by the function , Any modification of this variable in the function does not affect the parameters specified in the function call .
reference parameter : The variables handled by the function are the same as those used in the function call , Not just variables with the same value .
ref: Ensure that the parameter does not assign a new address to the new parameter .
although strings Is a reference type , But it is a special case , Because they are unchangeable . Modifying them will produce new string, The original string Will be deallocated . If you try to pass ref return string, be C# compiler Roslyn Will report a mistake .
Output parameters
- Use an unassigned variable as ref Argument is illegal , But you can use the assigned as out function .
- In addition, the function uses out The time of the function , It must be regarded as not yet assigned .
Tuples
The declaration form of tuples is illustrated by the following example :
private static (int max ,int min, double average)
GetMaxMin(IEnumerable<int> numbers)
{
return (
Enumerable.Max(numbers),
Enumerable.Min(numbers),
Enumerable.Average(numbers));
}
Then run the following code under a simple console application :
static void Main(string[] args)
{
IEnumerable<int> numbers = new int[] {
1,2,3,4,5,6 };
var result = GetMaxMin(numbers);
WriteLine($"Max number is {result.max},"+
$"Min number is {result.min},"+
$"Average is {result.average}."
);
Tuples provide a very convenient and direct way to return multiple values from a function , When no structure or more complex implementation is required in the program , It is very convenient, fast and effective to use the tuple .
边栏推荐
- Flutter dart regular regexp matches non printing characters \cl\cj\cm\ck
- Some knowledge of the beginning of 2022
- 微服務系統設計——子服務項目構建
- Ten excellent business process automation tools for small businesses
- congratulate! The first dragon lizard community annual outstanding contribution award is announced. Check it now
- Network security database penetration of secondary vocational group in 2022
- Data driven decision making: Decision intelligence and design thinking
- Does the wave of layoffs in Chinese enterprises in 2021 need to be "judged" by morality?
- R language Quantitative Ecology redundancy analysis RDA analysis plant diversity species data visualization
- Rapidssl getting started SSL certificate
猜你喜欢

How MySQL works - Chapter 14

110. balanced binary tree
![[NLP] 3 papers on how Stanford team builds a better chat AI](/img/f1/1c2ff31a728152395618800600df45.jpg)
[NLP] 3 papers on how Stanford team builds a better chat AI
R language Quantitative Ecology redundancy analysis RDA analysis plant diversity species data visualization

Considerations for it project demand analysis

Mcu-08 interrupt system and external interrupt application

2022 network security C module of the secondary vocational group scans the script of the surviving target aircraft (municipal, provincial and national)

The country has made a move! Launch network security review on HowNet

Project Management Guide: tips, strategies and specific practices

How to use Fisher's least significant difference (LSD) in R
随机推荐
2022 network security C module of the secondary vocational group scans the script of the surviving target aircraft (municipal, provincial and national)
Considerations for it project demand analysis
Online sequence flow chart making tool
How about China Power Investment Xianrong futures? Is it safe to open futures accounts?
如何在 R 中执行稳健回归
congratulate! The first dragon lizard community annual outstanding contribution award is announced. Check it now
Rapidssl getting started SSL certificate
Uniapp wechat applet calls mobile map to navigate to the target point
如何在 R 中执行幂回归
JS picture display and hiding cases
JS deep understanding of functions
Selection (030) - what is the output of the following code?
Leetcode topic [array] -216- combined sum III
Microservice system design - sub service project construction
Usage of typedef enum (enumeration)
How can an enterprise successfully complete cloud migration?
Mariana Trench, Facebook's open source code analysis tool
Why should state-owned enterprises accelerate the digital transformation
Application service access configuration parameters
JS local storage