C#委托 delegate

本文通过一个C#程序实例介绍了如何使用委托来封装不同的方法,并根据用户输入选择执行加法或乘法运算。文章展示了静态方法的直接引用及通过new关键字创建委托实例的方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test1
{
    class Program
    {
        public  delegate double MProcess(double a, double b);
        public static double Add(double a, double b)
        {
            return a + b;
        }
        public static double Multity(double a, double b)
        {
            return a * b;
        }
        static void Main(string[] args)
        {
            while (true)
            {
                int choose = Convert.ToInt32(Console.ReadLine());
                MProcess process;
                if (choose == 1)//赋值方式 
                {
                    process = Add;
                }
                else if(choose == 2)
                {
                    process = Multity;
                }
                else if (choose == 11)//new 方式
                {
                    process = new MProcess(Add);
                }
                else
                {
                    process = new MProcess(Multity);
                }
                string r = Console.ReadLine();
                string[] pars = r.Split(new char[1] { ' ' });
                int a = Convert.ToInt32(pars[0]);
                int b = Convert.ToInt32(pars[1]);
                Console.WriteLine("Result : {0}", process(a, b));

            }
        }
    }
}
### C#委托 (Delegate) 的用法 #### 委托的基本概念 在 C# 中,`delegate` 是一种类型安全的函数指针。它可以指向并调用一个或多个方法[^1]。通过 `delegate`,可以在运行时动态绑定方法,并允许将方法作为参数传递。 --- #### 示例代码解析 以下是基于引用中的示例代码解释: ```csharp class Program { static void OtherClassMethod(){ Console.WriteLine("Delegate an other class's method"); } static void Main(string[] args) { var test = new TestDelegate(); // 将实例方法赋值给委托 test.delegateMethod = new TestDelegate.DelegateMethod(test.NonStaticMethod); // 添加静态方法到委托 test.delegateMethod += new TestDelegate.DelegateMethod(TestDelegate.StaticMethod); // 绑定另一个类的方法到委托 test.delegateMethod += Program.OtherClassMethod; // 调用委托链中的所有方法 test.RunDelegateMethods(); } } class TestDelegate { public delegate void DelegateMethod(); // 定义委托类型 public DelegateMethod delegateMethod; // 实例化委托对象 public static void StaticMethod() { Console.WriteLine("Delegate a static method"); } public void NonStaticMethod() { Console.WriteLine("Delegate a non-static method"); } public void RunDelegateMethods() { if (delegateMethod != null){ Console.WriteLine("---------"); delegateMethod.Invoke(); // 执行委托链中的所有方法 Console.WriteLine("---------"); } } } ``` --- #### 代码说明 1. **定义委托类型** - 使用关键字 `public delegate` 定义一个新的委托类型 `DelegateMethod`,其签名为空参数列表和无返回值。 2. **实例化委托** - 创建委托类型的变量 `delegateMethod` 并将其初始化为某个具体方法(如 `NonStaticMethod`)。此操作表示将该方法绑定到委托上[^4]。 3. **组合多个方法** - 利用运算符 `+=` 可以向同一个委托附加额外的方法。这些方法会按照它们被添加的顺序执行[^3]。 4. **触发委托** - 当调用 `test.RunDelegateMethods()` 方法时,内部会对 `delegateMethod` 对象进行检查是否存在有效绑定;如果存在,则逐一调用其中所关联的所有方法[^1]。 5. **跨类支持** - 不仅限于当前类内的成员函数,还可以轻松实现对外部类公开接口的支持,比如这里展示了如何让程序外部的一个独立方法参与进来[^5]。 --- #### 输出结果分析 假设以上代码被执行后,控制台打印如下内容: ``` --------- Delegate a non-static method Delegate a static method Delegate an other class's method --------- ``` 每条消息对应着之前分别加入至 `delegateMethod` 队列里的三个不同来源的操作逻辑。 --- ### 总结 C# 中的 `delegate` 提供了一种灵活机制用于间接访问目标方法,尤其适用于事件处理模型以及回调场景下非常有用。它不仅能够单独代表某单一动作表达式,还具备串联多步流程的能力,在实际开发过程中有着广泛的应用价值。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值