C# action委托使用
时间: 2024-06-14 08:05:48 浏览: 10
C#中的Action委托是一个预定义的委托类型,它可以引用一个没有返回值的方法。Action委托可以用于指向不同参数类型和不同参数个数的方法。
以下是使用Action委托的几个示例:
1. 指向没有参数的方法:
```csharp
static void PrintString()
{
Console.WriteLine("hello world");
}
static void Main()
{
Action a = PrintString;
a(); // 输出:hello world
}
```
2. 指向有一个int类型参数的方法:
```csharp
static void PrintNumber(int num)
{
Console.WriteLine("The number is: " + num);
}
static void Main()
{
Action<int> a = PrintNumber;
a(10); // 输出:The number is: 10
}
```
3. 指向有一个string类型参数的方法:
```csharp
static void PrintMessage(string message)
{
Console.WriteLine("The message is: " + message);
}
static void Main()
{
Action<string> a = PrintMessage;
a("Hello"); // 输出:The message is: Hello
}
```
4. 指向有一个int类型参数和一个string类型参数的方法:
```csharp
static void PrintInfo(int num, string message)
{
Console.WriteLine("The number is: " + num);
Console.WriteLine("The message is: " + message);
}
static void Main()
{
Action<int, string> a = PrintInfo;
a(10, "Hello"); // 输出:The number is: 10 The message is: Hello
}
```
需要注意的是,Action委托没有返回值,但是可以通过在Action后面声明泛型来指定方法的参数类型。方法参数类型和Action后面声明的委托类型是要对应的。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)