.NET基础加强第八课--委托
- 委托(Delegate)
- 委托操作顺序
- 实例
- 多播委托—委托链
- 实例
- 实例委托传值
委托(Delegate)
委托(Delegate) 是存有对某个方法的引用的一种引用类型变量
委托操作顺序
1,定义一个委托类型
2,声明了一个委托变量 并且new 了一个委托对象,并且把方法传进去
3,调用委托相当于调用了方法
实例
//2, 声明了一个委托变量 md ,并且new 了一个委托对象,并且把方法M1传进去
using System.Text;
using System.Text.RegularExpressions;
MyDelegate md = new MyDelegate(M1);
// 3, 调用md委托相当于调用了M1 方法;
while (true)
{
Console.WriteLine(“请输入一个邮箱”);
string email = Console.ReadLine();
email = Regex.Replace(email, @“(\w+)(@\w+.\w+)”, ReplaceMethod,
RegexOptions.ECMAScript);
}
Console.ReadKey();
static void M1()
{
Console.WriteLine(“M1方法”);
}
static string ReplaceMethod(Match match)
{
string uid = match.Groups[1].Value;
string others = match.Groups[2].Value;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < uid.Length; i++)
{
sb.Append(“*”);
}
return sb.ToString() + others;
}
//1. 定义一个委托类型,用来保存无参数,无返回值的方法
public delegate void MyDelegate();
public delegate void WriteTimeDelegate();
public class MyClass
{
}
多播委托—委托链
实例
Action action = M1;
//action(“tttt”);
action += M2;
action += M3;
action += M4;
action(“hello”);
Console.ReadKey();
static void M1(string msg)
{
Console.WriteLine(msg);
}
static void M2(string msg)
{
Console.WriteLine(msg);
}
static void M3(string msg)
{
Console.WriteLine(msg);
}
static void M4(string msg)
{
Console.WriteLine(msg);
}
实例委托传值
代码明细
Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(textBox1.Text.Trim(),UpdateTextBox) ;
form2.ShowDialog();
}
UpdateTextDelegate md = new UpdateTextDelegate(D1);
static void D1(string value)
{
}
public void UpdateTextBox(string val)
{
textBox1.Text = val;
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
public delegate void UpdateTextDelegate(string val);
Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private UpdateTextDelegate _update;
public Form2(string value,UpdateTextDelegate updateText):this()
{
this.textBox1.Text = value;
this._update = updateText;
}
private void button1_Click(object sender, EventArgs e)
{
// 将当前窗体中的文本框中的值传给 窗体1
this._update(textBox1.Text.Trim());
this.Close();
}
private void Form2_Load(object sender, EventArgs e)
{
}
}