怪奇物语

怪奇物语

首页 新随笔 联系 管理

# 委托类型 函数别名

DeleGate\Program.cs


using System;

class Program
{
    // 定义一个委托类型
    public delegate void OperationDelegate(int x, int y);

    public static void Add(int x, int y)
    {
        Console.WriteLine($"Adding {x} and {y}: Result = {x + y}");
    }

    public static void Subtract(int x, int y)
    {
        Console.WriteLine($"Subtracting {y} from {x}: Result = {x - y}");
    }

    /// <summary>
    /// 1. 委托类型的参数可以看作是相同参数类型方法的别名
    /// 2. 通过这个别名来临时切换要执行的函数
    /// </summary>
    /// <param name="args"></param>
    static void Main(string[] args)
    {
        OperationDelegate operation;

        // 将方法 Add 分配给委托
        operation = Add;
        operation(5, 3); // 调用 Add 方法

        // 将方法 Subtract 分配给委托
        operation = Subtract;
        operation(5, 3); // 调用 Subtract 方法
    }
}

posted on 2024-08-31 11:56  超级无敌美少男战士  阅读(16)  评论(0)    收藏  举报