温馨提示×

c# function与Lambda表达式

c#
小樊
86
2024-07-22 20:44:04
栏目: 编程语言

Function in C# is a block of code that performs a specific task and can be called multiple times in a program. Functions in C# are defined using the “function” keyword followed by the function name, parameters, return type, and body of the function.

Lambda expressions in C# are a concise way to define anonymous functions. They are often used to create delegates or expression tree types. Lambda expressions are defined using the "=> " operator, where the parameters are on the left side of the operator and the expression or statement to be executed is on the right side.

Here is an example of a function in C#:

public int Add(int a, int b)
{
    return a + b;
}

And here is an example of a Lambda expression in C#:

Func<int, int, int> Add = (a, b) => a + b;

In the above example, the function “Add” takes two integer parameters and returns their sum. The Lambda expression also performs the same task, but in a more concise way. Lambda expressions are often used in LINQ queries, event handlers, and other scenarios where a short, inline function is needed.

0