C#中的委托(Delegate)
什么是委托?
首先,我们要知道C#是一种强类型的编程语言,强类型的编程语言的特性,是所有的东西都是特定的类型
委托是一种存储函数的引用类型,就像我们定义的一个 string str 一样,这个 str 变量就是 string 类型. 因为C#中没有函数类型,但是可以定义一个委托类型,把这个函数赋值给这个委托
//声明委托
//delegate 返回值类型 委托的名字(方法的参数)
delegate <return type> <delegate-name><parameter list>
//声明一个委托,接收string参数,返回值为int类型
pubulic delegate int MyDelegate(string s)
委托一旦被声明,就可以用new关键字来创建声明委托
委托的使用
方法一:
public delegate int MyDelegate(string s);
internal class Program
{
static void Main(string[] args)
{
MyDelegate d1 = new MyDelegate(Number);
d1("11");
}
static int Number(string b)
{
Console.WriteLine("你好"+b);
return 1;
}
}
方法二:
public delegate int MDelegate(string a);
internal class Program
{
static void Main(string[] args)
{
Test.TestT(Num);
}
static int Num(string str)
{
Console.WriteLine("你好"+str);
return 1;
}
}
class Test
{
public static void TestT(MDelegate aa)
{
//方法接收一个委托类型的参数,就相当于接收了一个方法,该方法必须满足这个委托的规定的参数和返回值
//aa 回调函数:以参数的形式传递到函数中的函数
aa("12");
}
}
实例化委托
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 委托实例化
{
delegate void Mystring(int x, string y);
delegate int NumberOper(int aa, int bb);
internal class Program
{
static void Main(string[] args)
{
new Test();
Mystring mystring=new Mystring(Fn);
mystring(1, "aaa");
}
static void Fn(int x, string y)
{
Console.WriteLine("Helloween");
}
}
class Test
{
public Test()
{
string str = "2025";
Mystring mystring=new Mystring(Fn);
mystring(1,str);
NumberOper sum = new NumberOper(Add);
Console.WriteLine(Add(20,30));
}
void Fn(int x, string y)
{
Console.WriteLine($"x==={x},y==={y}");
}
int Add(int a, int b)
{
return a + b;
}
}
}
什么是多播委托?
一个委托可以引用多个方法,可以依次调用所有引用的方法。可以通过使用+运算符来合并委托或使用-运算符来移除特定的方法实现。
delegate void MyDelegate(string name);
internal class Program
{
static void Main(string[] args)
{
//包含多个方法的委托,称之为多播委托
MyDelegate fns = new MyDelegate(Fn1);
//使用+=运算符, 再委托变量上再次添加一个方法
fns += new MyDelegate(new Test().Fn2);
}
public static void Fn1(string a)
{
Console.WriteLine($"这是Fn1中的a==={a}");
}
}
class Test
{
public void Fn2(string x)
{
Console.WriteLine($"这是Fn2中的a==={x}");
}
public static void Fn3(string x)
{
Console.WriteLine($"这是Fn3中的a==={x}");
}
}
多波委托你也可以理解为捆绑事件,一个按钮绑定了多个功能
例如:
C# Winform 全选/反选(CheckBox)控件-CSDN博客