C#委托的基本使用流程
【1】声明委托(方法的原型)
【2】根据委托编写具体方法
【3】定义委托变量
【4】将具体方法和委托变量关联
【5】使用委托变量
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 委托的使用01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
//【2】根据委托编写具体方法
static void Lecture1()
{
Console.WriteLine("我们正在学习C#委托技术!");
}
static void Lecture11()
{
Console.WriteLine("我们正在学习WPF开发技术!");
}
static void Lecture111()
{
Console.WriteLine("我们正在学习项目实战开发技术!");
}
static string Lecture2(int count, string course)
{
return $" {course} 课时 {count}";
}
static string Lecture22(int count, string course)
{
return $" {course} 课时 {count}";
}
/// <summary>
/// 使用委托
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//【3】定义委托变量
LectureDelegate1 lecture1 = null;
//【4】将具体方法和委托变量关联
lecture1 = Lecture1;
lecture1 += Lecture11;
lecture1 += Lecture111;
//【5】使用委托变量
lecture1();
// lecture1.Invoke(); //委托特有的Invoke();
Console.WriteLine("************************************");
lecture1 -= Lecture1;
lecture1();
Console.WriteLine("************************************");
LectureDelegate2 lecture2 = Lecture2;
Console.WriteLine(lecture2(200, ".NET高级编程"));
}
}
//【1】声明委托(方法的原型)
public delegate void LectureDelegate1();
public delegate string LectureDelegate2(int num, string content);
}