委托很好用,c#的委托有点函数指针的感觉,它能简化判断语句的使用,还能为窗口添加新的事件。
weituo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace fenzhi
{
public delegate int AddDelegate(int x, int y);
public class weituo
{
static public int Add(int x, int y)
{
return x + y;
}
static public int Add1(int x, int y)
{
return x - y;
}
static public int Add2(int x, int y)
{
return x * y;
}
public int Add3(int x, int y)
{
return x / y;
}
}
}
Form2.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace fenzhi
{
public partial class Form2 : Form
{
//委托事件
public delegate void ChangeEventHandler(string s);//声明为delegate 型的事件;
public event ChangeEventHandler TChange;//指定一个事件的名称
public Form2()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (TChange!=null)
TChange(textBox1.Text);
}
}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace fenzhi
{
public partial class Form1 : Form
{
/*委托的作用主要是两个:
1、 委托类方法,这种委托主要是为了调用类的不同方法,减少else判断的使用
2、委托事件:这种委托,是声明一个委托,然后让这个委托+=一些方法,也就是当触发了这个委托事件的时候就会触发+=的那个函数方法,也可以在方法中传值。
*/
public Form1()
{
InitializeComponent();
AddDelegate add;
add = new AddDelegate(new weituo().Add3);
add = new AddDelegate(weituo.Add);
textBox1.Text = add(1, 2).ToString();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.TChange += new Form2.ChangeEventHandler(f_TChange);
//f.TChange -= new Form2.ChangeEventHandler(f_TChange);
f.Show();
}
void f_TChange(string s)
{
textBox2.Text = s;
}
}
}
实现的情况是,如果修改了Form2的text,然后text1中的内容也会随着改变。
大概思路就是,Form2中添加委托,触发条件是textchange,然后在Form1中添加委托函数,如果Form2触发了条件,调用了委托,委托执行了函数,然后就成功改变了Form1中的text。这就是委托比较好用的地方。
以上是委托事件的实现。
还有就是委托函数,用委托来调用函数,这样可以减少if-else的使用。