using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms;namespace WindowsFormsApplication18 { public partial class Form1 : Form { delegate void ShowText(String S); // 定义函数指针原型 public Form1() { InitializeComponent(); ShowText P = DoShowText; // 定义一个函数指针指向函数,这样这个指针存的就是函数的入口地址 P("GO"); // 利用函数指针调用函数 } void DoShowText(String Text) { MessageBox.Show(Text); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms;namespace WindowsFormsApplication18 { public partial class Form1 : Form { delegate void ShowText(String S); // 函数定义 ShowText DelegateList = null; // 定义一个函数指针空列表 public Form1() { InitializeComponent();
http://msdn.microsoft.com/zh-cn/30cyx32c(VS.80).aspx委托可以简单近似理解为C++里的函数指针A+=B
等于
A->d1
d2
d3
最后加上
A->d1
d2
d3
B返回A无非最后添加一个方法的入口指针或新委托方法(一个指针)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;namespace WindowsFormsApplication18
{
public partial class Form1 : Form
{
delegate void ShowText(String S); // 定义函数指针原型
public Form1()
{
InitializeComponent();
ShowText P = DoShowText; // 定义一个函数指针指向函数,这样这个指针存的就是函数的入口地址
P("GO"); // 利用函数指针调用函数
}
void DoShowText(String Text)
{
MessageBox.Show(Text);
}
}
}
委托可以简单近似理解为C++里的函数指针数组
______
A->| d1 |
______
| d2 |
______
| d3 |
______
| B |
______
比如:P+=DoShowText;可以P+=new ShowText(DoShowText);也可以
而Combine()要求的是一个delegate,那么P+=DoShowText;这句里面函数名相应的隐式转换为一个ShowText了吗?
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;namespace WindowsFormsApplication18
{
public partial class Form1 : Form
{
delegate void ShowText(String S); // 函数定义
ShowText DelegateList = null; // 定义一个函数指针空列表
public Form1()
{
InitializeComponent();
MessageBox.Show("开始第一次调用");
DelegateList += DoShowText; // 函数的入口地址直接加入委托列表,内部列表+1,内容存放函数的入口地址
DelegateList("1个函数指针,所以现在输出1次"); // 利用函数指针调用函数 MessageBox.Show("开始第二次调用");
ShowText P = new ShowText(DoShowText);
DelegateList += P; // 函数指针加入委托列表,内部列表+1,内容存放函数指针的地址,而函数指针指向函数入口地址,所以其实等于指向函数的入口地址
DelegateList("2个函数指针,所以现在输出2次"); // 利用函数指针调用函数
}
void DoShowText(String Text)
{
MessageBox.Show(Text);
}
}
}