delegate它允许你传递一个类A的方法m给另一个类B的对象,使得类B的对象能够调用这个方法m比如:A界面修改了一个值,在B界面上能马上显示出来并不需要重新刷新。action和func 的区别是action是无返回值 而func是有返回值的。如果是在同一个页面上实现的效果都是一样的, “线程间操作无效: 从不是创建控件“textBox1”的线程访问它” 出现了这样的错误就可以利用delegate 或者action或者func就可以解决。下面就可以看例子:
delegate委托 Form3界面调用Form2界面的方法例子:
Form2界面
public delegate void testDelegate();
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public void Test(){
MessageBox.Show("Form2的Test方法已被调用!");
}
private void Form2_Load(object sender, EventArgs e)
{
Form3 form3=new Form3();
form3.testCallBack=Test;//已经把form2的方法赋给了form3的testCallBack
form3.ShowDialog();
}
}
Form3界面
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
testCallBack();
}
public testDelegate testCallBack;
}
delegate 委托 在界面上调用方法:
public delegate void bTest();
public bTest bTestCallBack;
public void Test()
{
Console.WriteLine("测试");
}
private void Form1_Load(object sender, EventArgs e)
{
bTestCallBack = new bTest(Test);//已经把Test赋给了bTestCallBack
// 以后调用可以this.Invoke(bTestCallBack)
//主要解决错误:线程间操作无效: 从不是创建控件“textBox1”的线程访问它
}
Action委托 在界面上调用方法(无返回值):
public void CTest(IAsyncResult IR)
{
Action bt = (Action)IR.AsyncState;
bt.EndInvoke(IR);
Console.WriteLine("结束测试");
}
public void Test()
{
Console.WriteLine(“开始测试”);
}
private void Form1_Load(object sender, EventArgs e)
{
//开始执行action中的Test方法执行完后就会执行 CTest方法
//delegate 和func都有BeginInvoke这个方法 如果被action无返回值用起来这个方法会比较爽
Action action = new Action(Test);
bTestCallBack.BeginInvoke(new AsyncCallback(CTest),action);
}
Func 委托 在界面上调用方法(有返回值):
public string Test2(){
return"开始测试";
}
public string Test3(string msg)
{
return msg;
}
public string Test4(string msg,string msg2)
{
msg = msg + msg2;
return msg;
}
private void Form1_Load(object sender, EventArgs e)
{
//无参数
Func<string> func=new Func<string>(Test2);
string ms=func();
//单个参数
Func<string,string> func2 = new Func<string,string>(Test3);
ms= func2("开始测试func2");
//多个参数
Func<string, string, string> func3 = new Func<string, string, string>(Test4);
ms = func3("开始测试func3","结束测试func3");
//Func<类> func=new Func<类>();返回值为类的也可以
}
以上就是使用delegate 、action和func的使用的例子。
MethodInvoker mk =()=>{
//要书写的代码
};
if(this.InvokeRequired){
this.Invoke(mk);
}else{
mk();
}
该委托表示可执行托管代码中声明为void 且不接受任何参数的方法。