委托(Delegate)是存有对某个方法的引用的一种引用类型变量,引用可在运行时被改变。委托(Delegate)特别用于实现事件和回调方法,所有委托(Delegate)都派生于System.Delegate类。(方法被当作方法的参数调用)
注意哦:C#中的委托(Delegate)类似于C或C++中函数的指针。
1、声明委托
委托声明决定了可由该委托引用的方法,委托可指向一个与其具有相同标签的方法。假设
public delegate int DelegateStr (string s);
这个委托可被用于任何一个带有一个单一的string参数的方法,并返回一个int类型变量。声明委托的语法如下:
delegate <return type> <delegate-name> <parameter list>
2、实例化委托以及应用
声明了委托类型,委托对象必须使用new关键字来创建,且与一个特定的方法有关,当创建委托时,传递到new语句的参数就像方法调用一样书写,但是不带有参数。
public delegate void BuyTicketDelegateEvent();
BuyTicketDelegateEvent delegateJay = new BuyTicketDelegateEvent(Wwo.BuyTicket);
BuyTicketDelegateEvent delegateGrape = new BuyTicketDelegateEvent(Wwo.BuyMoveTicket);
下面的实例演示了委托的声明、实例化和使用
namespace Delegate_Practise
{
public partial class Form1 : Form
{
public static string str;
public static string str2;
public delegate void BuyTicketDelegateEvent();
public Form1()
{
InitializeComponent();
//创建委托实例
BuyTicketDelegateEvent delegateJay = new BuyTicketDelegateEvent(Wwo.BuyTicket);
BuyTicketDelegateEvent delegateGrape = new BuyTicketDelegateEvent(Wwo.BuyMoveTicket);
//使用委托对象调用方法
delegateJay();
delegateGrape();
richTextBox1.Text = str + "\r\n" + str2 ;
}
public class Wwo
{
public static void BuyTicket()
{
str = "我喜欢听纠结伦的歌诶";
}
public static void BuyMoveTicket()
{
str2 = "还喜欢葡萄不愤怒乐队!!!";
}
}
}
}
运行结果:
3、委托的多播(Multicasting of a Delegate)
委托对象可以使用“+”运算符合并,一个合并委托可以调用它所合并的两个委托。(注意哦:只有相同类型的委托可被合并)“-”运算符可用于从合并的委托中移除组件委托。
namespace Delegate_Practise
{
public partial class Form1 : Form
{
delegate int Numberarithmetic(int W);
public Form1()
{
InitializeComponent();
// 创建委托实例
Numberarithmetic Add = new Numberarithmetic(AddNum);
Numberarithmetic Mult = new Numberarithmetic(MultNum);
Numberarithmetic Arithemtic;
Arithemtic = Add;
Arithemtic += Mult;
// 调用多播
Arithemtic(4);
richTextBox1.Text = $"Value of Num: {getNum()}";
}
static int num = 10;
public static int AddNum(int o)
{
num += o;
return num;
}
public static int MultNum(int o)
{
num *= o;
return num;
}
public static int getNum()
{
return num;
}
}
}
运行结果:
(对委托不是很了解,看了一些文章,学习并整理了一下,写得有些拙劣,但也希望能有帮助到!!!)