委托总结
//总结
//和outputTime();表达一样,编译器会把outputTime();编译成outputTime.Invoke();
//1 定义委托数据类型
//2 定义委托变量
//3 判断委托类型是否存在,使用委托
//if (outputTime != null)
// {
// //和outputTime();表达一样,编译器会把outputTime();编译成outputTime.Invoke();
// outputTime.Invoke();
// }
// 文件写入操作File.WriteAllText(@"aaa.text", System.DateTime.Now.ToString("yy-MM-dd hh-mm-ss"));
调试程序,在要查看的位置设置断点,F10下一步
一般程序,以两种方式显示时间(控制台和写入文件)
主程序: class Program { static void Main(string[] args) { Class1 t1 = new Class1(); t1.outputTime = M1; t1.output1_time(); Class2 t2 = new Class2(); t2.outputTime = M2; t2.output1_time(); Console.ReadKey(); } static void M1() { Console.WriteLine("当前时间:{0}", System.DateTime.Now.ToString()); } static void M2() { File.WriteAllText(@"aaa.text", System.DateTime.Now.ToString("yy-MM-dd hh-mm-ss")); } } 类 //定义一个委托类型 public delegate void dele_time(); public class Class1 { public dele_time outputTime; public void output1_time() { Console.WriteLine("--------------------------------------------------"); Console.WriteLine("--------------------------------------------------"); if (outputTime!=null) { outputTime(); } Console.WriteLine("--------------------------------------------------"); Console.WriteLine("--------------------------------------------------"); } } public class Class2 { public dele_time outputTime; public void output1_time() { Console.WriteLine("--------------------------------------------------"); Console.WriteLine("--------------------------------------------------"); if (outputTime != null) { //和outputTime();表达一样,编译器会把outputTime();编译成outputTime.Invoke(); outputTime.Invoke(); } Console.WriteLine("--------------------------------------------------"); Console.WriteLine("--------------------------------------------------"); } }
窗体间传值代码
1 定义委托类型 public delegate void dele_chuanzhi(string str); form1代码 private void button1_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.Show(); f2.chuanzhi = updateBtn; } private void updateBtn(string str) { textBox1.Text = str; } form2代码 private void textBox1_KeyUp(object sender, KeyEventArgs e) { //this.Text = textBox1.Text; string uInput = this.textBox1.Text; if (chuanzhi != null) { chuanzhi(uInput); } }
时间: 2024-11-04 18:09:27