首页 > Linux操作系统 > Linux操作系统 > c#委托delegate使用

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace learn_self_define_control { public partial class Form1 : Form { //声明一个委托类型 委托是对某个类型某个方法的引用,只要在符合这个规范就可调用 private delegate string ftxdelegate(string s); //定义一个委托类型的变量 ftxdelegate ftx; public Form1() { InitializeComponent(); } //选中单选按钮事件 checkedchanged private void radioButton1_CheckedChanged(object sender, EventArgs e) { button1.Enabled = true; //实例化委托类型的变量,其构造函数的参数就是具体每个类的方法(当然这个方法分为动与静态) ftx = new ftxdelegate(new Capital().fixText); } private void radioButton2_CheckedChanged(object sender, EventArgs e) { button1.Enabled = true; ftx = new ftxdelegate(Lower.fixText); } private void button1_Click(object sender, EventArgs e) { //ftx就是委托类型的变量 //ftx先定义然后初始化最后用它作事,返回string类型的s string s = ftx(textBox1.Text); listBox1.Items.Add(s); } } } |
| using System; using System.Collections.Generic; using System.Text; namespace learn_self_define_control { class Capital { //被委托类型变量(作为其参数使用)的类方法 public string fixText(string s) { //大写 return s.ToString().ToUpper(); } } class Lower { public static string fixText(string s) { //小写 return s.ToString().ToLower(); } } } |
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/9240380/viewspace-719397/ ,如需转载,请注明出处,否则将追究法律责任。