C# 委托(Delegate)学习笔记

什么是委托

C# 中的委托是一种类型,它用于引用一个或多个方法,可以将其视为函数指针。通过使用委托,可以使代码更灵活、更具适应性,因而在事件处理、回调函数等方面得到了广泛应用。

如何定义委托

定义委托时需要指定方法的参数类型和返回值类型,语法如下:

csharpCopy Code
public delegate returnType delegateName(parameterList);

例如,定义一个只有一个 int 类型参数并返回 int 类型的委托:

csharpCopy Code
public delegate int MyDelegate(int x);

委托的使用

实例化委托

实例化委托可以使用 new 关键字,其参数是要引用的方法名。例如:

csharpCopy Code
public class MyClass { public static int MyMethod(int x) { return x * 2; } } MyDelegate myDelegate = new MyDelegate(MyClass.MyMethod);

上述代码实例化了一个 MyDelegate 类型的委托,并将其引用了 MyClass 类中的 MyMethod 方法。

委托的调用

使用委托可以调用所引用的方法。例如:

csharpCopy Code
int result = myDelegate(5);

上述代码调用了 MyMethod 方法,并传递了参数 5,结果为 10

委托的多播

委托还支持多播,即将多个方法引用赋给一个委托。例如:

csharpCopy Code
MyDelegate myDelegate1 = new MyDelegate(MyClass.MyMethod); MyDelegate myDelegate2 = new MyDelegate(MyClass.MyMethod); MyDelegate multiDelegate = myDelegate1 + myDelegate2;

上述代码使用 + 运算符将两个委托引用组合成一个委托。此时,调用 multiDelegate 委托时,会依次调用 myDelegate1myDelegate2 引用的方法。

示例代码

以下是一个使用委托实现策略模式的示例代码:

csharpCopy Code
public interface IStrategy { void Algorithm(); } public class ConcreteStrategyA : IStrategy { public void Algorithm() { Console.WriteLine("执行策略A"); } } public class ConcreteStrategyB : IStrategy { public void Algorithm() { Console.WriteLine("执行策略B"); } } public class Context { private IStrategy _strategy; public Context(IStrategy strategy) { _strategy = strategy; } public void ExecuteStrategy() { _strategy.Algorithm(); } } static void Main(string[] args) { IStrategy strategyA = new ConcreteStrategyA(); IStrategy strategyB = new ConcreteStrategyB(); Context context = new Context(strategyA); context.ExecuteStrategy(); context = new Context(strategyB); context.ExecuteStrategy(); }

在上述代码中,定义了 IStrategy 接口,它包含一个算法方法 Algorithm。并定义了两个实现类 ConcreteStrategyAConcreteStrategyB,它们分别实现了 IStrategy 接口。还定义了 Context 类用于执行策略,其构造函数使用委托将具体的策略传入,并在 ExecuteStrategy 方法中调用。在 Main 方法中,使用委托实例化 Context 并执行不同的策略。

以上就是 C# 委托(Delegate)学习笔记。