窗体传值案例,首先创建2个窗体和两个按钮控件
//在窗体1中
public Form1()
{
InitializeComponent();
}
//点击给我过去按钮
private void button1_Click(object sender, EventArgs e)
{
//创建窗体2对象,将文本框内容和方法传过去
Form2 form2 = new Form2(textBox1.Text,Show);
form2.Show();
}
//将窗体2字符串赋值给窗体1的文本框
public void Show(string text)
{
textBox1.Text = text;
}
在窗体2中
//创建委托存储方法
public delegate void DelText(string text);
public partial class Form2 : Form
{
//写一个字段存储委托
private DelText _dt;
//接收窗体1传过来的文本和方法
public Form2(string text,DelText dt)
{
InitializeComponent();
//将接收的文本赋值给文本框
textBox1.Text = text;
//将委托对象赋值给字段
this._dt = dt;
}
//点击给我回去按钮
private void button1_Click(object sender, EventArgs e)
{
if (this._dt != null)
{
//调用窗体1的方法,将窗体2文本框内容传入
this._dt(textBox1.Text);
}
//关闭窗体2
this.Close();
}
委托
//声明委托
public delegate int DelAdd(int n1, int n2);
class Program
{
static void Main(string[] args)
{
int n3=Show(Add, 10, 20);
Console.WriteLine(n3);
Console.ReadKey();
}
public static int Show(DelAdd da,int n1,int n2)
{
Console.WriteLine($"现在的时间是{DateTime.Now}");
return da(n1,n2);
}
public static int Add(int num1,int num2)
{
return num1 + num2;
}
}
匿名函数
//声明一个委托
public delegate void Delegate();
public delegate void Delegate1(int n1);
public delegate int Delegate2(int n1, int n2);
class Program
{
static void Main(string[] args)
{
//写匿名函数
Delegate del = delegate () { Console.WriteLine("hhh"); };
//调用匿名函数
del();
Delegate1 del1 = delegate (int n1) { Console.WriteLine(n1); };
del1(10);
Delegate2 del2 = delegate (int n1, int n2) { return n1 + n2; };
int result=del2(10, 20);
Console.WriteLine(result);
Console.ReadKey();
}
}
拉姆达表达式
//创建委托
public delegate void Delegate();
public delegate void Delegate3(string name);
public delegate int Delegate1(int n1,int n2);
class Program
{
static void Main(string[] args)
{
//写拉姆达表达式
Delegate del = () => { Console.WriteLine("hhhhh"); };
del();
Delegate1 del1 = (n1,n2) => { return n1+n2; };
int result=del1(10,20);
Console.WriteLine(result);
Delegate3 del3 = (name) => { Console.WriteLine(name); };
del3("张三");
Console.ReadKey();
}
}