How is the function used in C#?

In C#, Func is a generic delegate type used to represent a method with specific parameters and return type. When using the Func delegate, you need to specify the types of the parameters and the return value.

以下是Func的定义:

public delegate TResult Func<in T, out TResult>(T arg);
public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
// ...

Delegate can have up to 16 parameters. The first generic parameter represents the type of the method’s parameters, and the last generic parameter represents the return value type of the method.

The steps to use a Func delegate are as follows:

  1. Define a method whose parameters and return type match those of the Func delegate.
  2. Create a Func delegate instance, specifying the method’s name as a parameter.
  3. Call the Invoke method of the Func delegate instance to execute the method.

Here is an example using the Func delegate:

// 定义一个方法,接受一个整数参数并返回字符串
static string ConvertToString(int number)
{
    return number.ToString();
}

// 使用Func委托
Func<int, string> convertFunc = ConvertToString; // 创建Func委托实例
string result = convertFunc.Invoke(123); // 调用委托的Invoke方法执行方法
Console.WriteLine(result); // 输出:123

In the example above, we defined a method called ConvertToString that takes an integer parameter and returns a string. Then, we created a Func delegate instance convertFunc, specifying the ConvertToString method as the parameter. Finally, we called the delegate’s Invoke method to execute the method and print the result to the console.

bannerAds