c#————委托Action使用例子

cs 复制代码
using System;

public class Program
{
    // 定义一个符合Action<int>签名的方法
    public static void PrintNumber(int number)
    {
        Console.WriteLine("The number is: " + number);
    }

    public static void Main(string[] args)
    {
        // 实例化一个Action<int>委托,并指向PrintNumber方法
        Action<int> printAction = PrintNumber;

        // 调用委托,传递一个整数参数
        printAction(42);

        // 你也可以直接将方法作为参数传递给另一个方法,而无需显式创建委托实例
        PerformAction(PrintNumber, 100);
    }

    // 一个接受Action<int>作为参数的方法
    public static void PerformAction(Action<int> action, int value)
    {
        // 调用传入的委托
        action(value);
    }
}
cs 复制代码
using System;

class Program
{
    static void Main(string[] args)
    {
        // 定义几个方法
        void PrintNumber(int number)
        {
            Console.WriteLine($"Number: {number}");
        }

        void DoubleAndPrint(int number)
        {
            Console.WriteLine($"Double: {number * 2}");
        }

        void SquareAndPrint(int number)
        {
            Console.WriteLine($"Square: {number * number}");
        }

        // 创建一个Action<int>委托,并添加多个方法
        Action<int> printAction = PrintNumber;
        printAction += DoubleAndPrint;
        printAction += SquareAndPrint;

        // 调用委托,将依次执行所有附加的方法
        printAction(5);
    }
}

在这个例子中,我们定义了三个方法:PrintNumberDoubleAndPrintSquareAndPrint。然后我们创建了一个 Action<int> 类型的委托 printAction,并将这三个方法都附加到了这个委托上。当我们用参数 5 调用 printAction 时,它会依次执行这三个方法,输出结果如下:

|---|------------------|
| | Number: 5 |
| | Double: 10 |
| | Square: 25 |

这样,你就可以通过将一个 Action<int> 委托与多个方法关联,实现更复杂的逻辑。如果你想要在某个时刻移除某个方法,也可以使用 -= 运算符,例如:

|---|--------------------------------------|
| | printAction -= DoubleAndPrint; |

这将从委托中移除 DoubleAndPrint 方法,使得再次调用 printAction 时不再执行该方法。

相关推荐
弹简特1 天前
【Java项目-轻聊】05-AI赋能设计接口文档
java·开发语言
达达爱吃肉1 天前
claude 接入deepseek 运行报错
java·服务器·前端
OctShop大型商城源码1 天前
OctShop对比JAVA商城源码_OctShop大型专业级多用户商城源码
java·开发语言·商城系统·小程序商城·octshop
guslegend1 天前
AGENT.md,Skill与工程规范
java·开发语言·数据库
jingling5551 天前
Flutter | Dio网络请求实战
android·开发语言·前端·flutter
周末也要写八哥1 天前
C++中单线程方式之无脑上锁
java·开发语言·c++
魔法阵维护师1 天前
从零开发游戏需要学习的c#模块,第三十一章(技能冷却系统 —— 范围爆炸)
学习·游戏·c#
freeinlife'1 天前
精准秒表计时器实现---基于js
开发语言·前端·javascript
Reisentyan1 天前
[Advance]GoLang Learn Data Day 4
java·数据库·golang
MaCa .BaKa1 天前
55-宠物爱心救助领养系统-宠物救助领养系统
java·vue.js·tomcat·maven·springboot·宠物救助领养系统