委托的标准定义是,委托是一种引用类型,表示对具有特定参数列表和返回类型的方法的引用;
在实例化委托时,你可以将其实例与任何具有兼容签名和返回类型的方法相关联;
还有一种定义看上去也是正确的:委托是一种引用类型变量,用于存储某个方法的引用地址;
委托类似于 C++ 函数指针,但委托完全面向对象,不像 C++ 指针会记住函数,委托会同时封装对象实例和方法。
一个示例;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
-
- namespace mywt1
- {
- public partial class Form1 : Form
- {
- public delegate int mycal(int x, int y);
-
- public Form1()
- {
- InitializeComponent();
- }
-
- private void button1_Click(object sender, EventArgs e)
- {
- mycal cal1 = new mycal(Add);
- mycal cal2 = new mycal(Multiply);
-
- textBox1.Text = cal1.Invoke(9, 10).ToString();
- textBox2.Text = cal2.Invoke(11, 3).ToString();
- }
-
- static private int Add(int x, int y)
- {
- return x+y;
- }
-
- static private int Multiply(int x, int y)
- {
- return x*y;
- }
- }
- }
public delegate int mycal(int x, int y);
定义了委托 mycal,参数是2个int类型,返回值类型是int;
实例化 cal1 为对Add方法的引用, cal2 为对Multiply方法的引用;然后用cal1和cal2调用了方法,返回结果;