当前位置:网站首页>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 .
边栏推荐
- Software testing methods: a short guide to quality assurance (QA) models
- Uniapp wechat applet calls mobile map to navigate to the target point
- Microservice system design - sub service project construction
- 微服务系统设计——子服务项目构建
- The mixed calculation of rpx and PX in JS by the uniapp applet
- Tencent cloud won the "trusted cloud technology best practice - virtualization"
- He "painted" what a smart city should look like with his oars
- Recommend 14 commonly used test development tools
- What is business intelligence (BI)?
- How to perform power regression in R
猜你喜欢

Wechat applet to realize stacked rotation

Several key points for enterprises to pay attention to digital transformation

JS deep understanding of functions

Different JVM

SAP license: SAP s/4 Hana module function introduction
[North Asia data recovery]_ mdb_ catalog. Mongodb database data recovery case in case of WT file corruption

Two micro service interviews where small companies suffer losses

SAP license: ERP for supply chain management and Implementation

How to use Fisher's least significant difference (LSD) in R

Conception de systèmes de micro - services - construction de sous - services
随机推荐
Gateway solves cross domain access
如何在 R 中执行幂回归
Data modeling technology of Business Intelligence BI
Selection (030) - what is the output of the following code?
Flutter dart regular regexp matches non printing characters \cl\cj\cm\ck
微服务系统设计——接口文档管理设计
【leetcode】838. Push domino (Analog)
Leetcode weekly buckle 281
Tencent cloud won the "trusted cloud technology best practice - virtualization"
360 digital released information security trends in January: 120000 fraud risks were captured and users were reminded 2.68 million times
Project Management Guide: tips, strategies and specific practices
How does the video platform import the old database into the new database?
How to create a linear model prediction interval in R and visualize it
Sword finger offer 10- ii Frog jumping on steps
Wechat applet development - Implementation of rotation chart
Application service access configuration parameters
What are the grades of financial products?
130. surrounding area
Window object
Leetcode question 136 [single number]