Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีเรียกใช้การดำเนินการทางคณิตศาสตร์ด้วย Delegate ใน C#

การใช้ Delegate เรียกใช้การดำเนินการทางคณิตศาสตร์ใน C#

Delegate เป็นชนิดข้อมูลที่อ้างอิงถึงเมธอด (type-safe function pointer) ช่วยให้ส่งเมธอดเป็นพารามิเตอร์ เก็บในตัวแปร หรือเรียกใช้แบบไดนามิกได้

ตัวอย่าง: ใช้ Delegate กับการหาร

using System;

public class Demo
{
    // เมธอดสำหรับหาร 5
    public static double DivideFunc(double value)
    {
        return value / 5;
    }

    // ประกาศ Delegate
    delegate double MyDelegate(double x);

    static void Main()
    {
        // สร้างอาร์เรย์ Delegate
        MyDelegate[] operations = { DivideFunc };

        // เรียกใช้ผ่านเมธอดช่วย
        Result(operations[0], 20); // 20 / 5 = 4
        
        // หรือเรียกโดยตรง
        double direct = operations[0](30); // 30 / 5 = 6
        Console.WriteLine($"Direct call: {direct}");
    }

    // เมธอดรับ Delegate เป็นพารามิเตอร์
    static void Result(MyDelegate d, double value)
    {
        double result = d(value); // เรียก Delegate
        Console.WriteLine($"Result = {result}");
    }
}

ผลลัพธ์


Result = 4
Direct call: 6

รูปแบบ Delegate ทันสมัย: Func และ Action

แทนที่จะประกาศ delegate เอง ใช้ Func<T, TResult> และ Action<T> ใน namespace System


using System;

class Program
{
    static void Main()
    {
        // Func - มีคืนค่า
        Func divideBy5 = x => x / 5;
        Func add = (a, b) => a + b;
        
        // Action - ไม่มีคืนค่า (void)
        Action print = x => Console.WriteLine($"Value: {x}");

        // ใช้งาน
        double result = divideBy5(25); // 5
        print(result);
        
        double sum = add(10, 20); // 30
        print(sum);
        
        // ส่งเป็นพารามิเตอร์
        ApplyOperation(100, divideBy5);
        ApplyOperation(50, x => x * 2); // Lambda inline
    }

    static void ApplyOperation(double value, Func operation)
    {
        double result = operation(value);
        Console.WriteLine($"Operation result: {result}");
    }
}

ตัวอย่างครบ: Calculator ด้วย Delegate


using System;
using System.Collections.Generic;

class Calculator
{
    // Dictionary เก็บ operation ตามชื่อ
    private Dictionary> operations 
        = new Dictionary>();

    public Calculator()
    {
        operations["+"] = (a, b) => a + b;
        operations["-"] = (a, b) => a - b;
        operations["*"] = (a, b) => a * b;
        operations["/"] = (a, b) => b != 0 ? a / b : double.NaN;
        operations["^"] = (a, b) => Math.Pow(a, b);
    }

    public double Calculate(double a, string op, double b)
    {
        if (operations.TryGetValue(op, out var func))
            return func(a, b);
        throw new ArgumentException($"Unknown operator: {op}");
    }
}

class Program
{
    static void Main()
    {
        var calc = new Calculator();
        Console.WriteLine(calc.Calculate(10, "+", 5));  // 15
        Console.WriteLine(calc.Calculate(10, "^", 2));  // 100
        Console.WriteLine(calc.Calculate(10, "/", 0));  // NaN
    }
}

Delegate vs Interface vs Lambda

ลักษณะDelegateInterfaceLambda
หลายเมธอดไม่ได้ (เดี่ยว)ได้ไม่ได้ (เดี่ยว)
Statefulได้ (closure)ได้ได้ (closure)
SyntaxVerboseClass/Structกระชับ
เหมาะสำหรับCallback, Event, StrategyContract, Multiple methodsInline, LINQ, Delegate