C#委托实例
来源:互联网 发布:ios编程用什么语言 编辑:程序博客网 时间:2024/04/29 18:37
//委托是一个特殊的类,它定义了方法的类型,可以将方法当作另一个方法的参数来进行传递,这种方法动态地赋给参数的做法,可以避免在程序中大量使用if-else(Switch)语句,同时也使得程序具有更好的扩展性。委托机制尤其适合在使用事件处理的编程模式或者类的静态方法,以及在需要封装和灵活的组织方法的场合
//实例1using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace linq{ //实例1 //简单的来说委托就是把方法当参数传 public delegate int testdelegate(int i);//定义委托 class Delegates { public int testfuck(int x) { Console.WriteLine(x * x); return x * x; } public int testfuck1(int x) { Console.WriteLine(x / x); return x / x; } }}// static void Main(string[] args) { Delegates dete = new Delegates(); testdelegate ts;//声明委托 ts = new testdelegate(dete.testfuck);//实例委托 ts += new testdelegate(dete.testfuck1);//多个绑定 ts(2); Console.ReadKey(); // linq1(); }//实例二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 Stockes{ public partial class DelegateForms : Form { public DelegateForms() { InitializeComponent(); } private void textBox1_TextChanged(object sender, EventArgs e) { } private delegate void writeTxtBox(char cha);//定义委托 private writeTxtBox writebox;//声明委托 private void button1_Click(object sender, EventArgs e) { if (radioButton1.Checked) { groupBox4.Text = "正在运行"; groupBox2.Refresh(); writebox = new writeTxtBox(writeText1);//实例委托 write(writebox); textBox1.Clear(); } else if (radioButton2.Checked) { groupBox5.Text="正在运行"; groupBox3.Refresh(); writebox = new writeTxtBox(writeText2);//实例委托 write(writebox); textBox2.Clear(); } groupBox4.Text = ""; groupBox5.Text = ""; } private void write(writeTxtBox write)//使用委托 { String txt3 = textBox3.Text; for (int i = 0; i < txt3.Length; i++) { write(txt3[i]); DateTime now = DateTime.Now; while (now.AddSeconds(1) > DateTime.Now){} } } public void writeText1(char str) { textBox1.AppendText(str.ToString()); } public void writeText2(char str) { textBox2.AppendText(str.ToString()); } }}