解释代表概念!

委托是定义方法签名的类型,并且可以保存对具有该签名的一个或多个方法的引用。

它们通常被描述或称为类型安全函数指针,因为它们允许将方法作为参数传递、分配给变量或动态调用,同时确保类型安全。🔒

代表们的重点是什么🗝️?

  • 方法签名:委托指定返回类型和它可以引用的方法的参数。
  • 类型安全:委托确保它们引用的方法具有正确的签名。
  • 多播:单个委托可以引用多个方法并按顺序调用它们。这称为多播委托。
  • 封装:委托封装方法及其行为,使其对于定义回调机制有用。
  • 那么委托的语法是什么?!

    // 1. Declare a Delegate..
    public delegate void MyDelegate(string message);
    
    // 2. Create a method matching the Delegate's signature
    public class Program {
    
      public static void DisplayMessage(string message) {
        Console.WriteLine(message);
      }
    
      public static void Main() {
        // 3. Instantiate the delegate
        MyDelegate del = DisplayMessage;
    
        // 4. Invoke the delegate
        del("Hellow, World!");
      }
    
    }

    让我们来谈谈常见的用途!

    有 3 种常见用途:

  • 事件处理
  • 回调机制
  • LINQ 和函数式编程
  • 让我们逐一解释一下

    1- 事件处理:委托是 C# 中事件的基础,它们允许使用方法订阅和取消订阅事件。

    public delegate void Notify();
    
    public class EventExample {
      public event Notify OnNotify;
    
      public void TriggerEvent() {
        OnNotify?.Invoke(); // Safely invoke the delegates if it has subscribers 
      }
    }

    2-回调机制:将一个方法传递给另一个方法以便稍后执行。

    public class Calculator {
      public void PerformOperation(int x, int y, Action callback) {
        int result = x + y;
        callback(result);
      }
    }
    
    public class Program {
      public static void Main() {
        Calculator calc = new ();
        calc.PerformOperation(2, 3, Console.WriteLine); // Pass Console.WriteLine as a Delegate
      }
    }

    3- LINQ 和函数式编程:LINQ 中大量使用 Func、Action、Predicate 等委托来定义自定义逻辑。

    什么是内置代表?

  • Action:表示没有返回值但有参数的方法。
  • Action print = Console.WriteLine;
    print("Hello, World!");
  • Func :表示有返回值和参数的方法。
  • Func add  (x,y) => x + y;
    Console.WriteLine(add(3,4));
  • Predicate:表示返回 bool 并且接受单个参数的方法。
  • Predicate IsEven = x => x % 2 == 0;
    Console.WriteLIne(IsEven(4));

    代表的优势

  • 灵活性 => 允许动态方法调用
  • 松散耦合 => 通过允许动态分配方法来提高代码的可扩展性
  • 可重用性 => 鼓励创建模块化、可重用的代码
  • 现在就这样了!继续编码,保持优秀。稍后见,书呆子们!