KimhillZhang  

摘自《MSDN》

 

可以使用 Action<T> 委托以参数形式传递方法,而不用显式声明自定义的委托。封装的方法必须与此委托定义的方法签名相对应。也就是说,封装的方法必须具有一个通过值传递给它的参数,并且不能返回值。(在 C# 中,该方法必须返回 void在 Visual Basic 中,必须通过 SubEnd Sub 结构来定义它。它也可以是返回已忽略的值的方法。)通常,这种方法用于执行某个操作。

 

在使用 Action<T> 委托时,不必显式定义一个封装只有一个参数的方法的委托

例如:

 

       public delegate void AppendDataDelegate(string message);
        public void AppendData(string message)
        {
            if (richTextBox1.InvokeRequired)
            {
                AppendDataDelegate d = new AppendDataDelegate(AppendData);
                richTextBox1.Invoke(d, new object[] { message });
            }
            else
            {
                Application.DoEvents();
                richTextBox1.AppendText(message + "\n");
            }
        }

或者

 

 this.richTextBox1.Invoke(new MethodInvoker(delegate()
{
           //...........
}));

 

可以写成:

 

      public void AppendData(string message)
        {
            this.richTextBox1.BeginInvoke((Action<string>)delegate(string mess) {
                richTextBox1.AppendText(mess);
            }, message);
        }

 

 

 

下面的示例演示如何使用 Action<T> 委托来打印 List<T> 对象的内容。演示如何使用匿名方法将内容显示出来。请注意该示例不显式声明 Action<T> 变量。相反,它传递方法的引用,该方法采用单个参数而且不将值返回至 List<T>.ForEach 方法,其单个参数是一个 Action<T> 委托。同样,在 C# 示例 中,Action<T> 委托不被显式地实例化,因为匿名方法的签名匹配 List<T>.ForEach 方法所期望的 Action<T> 委托的签名。

例如:

List<String> list = new List<string>();

            list.Add("1");
            list.Add("2");

 


            list.ForEach(delegate(string n) {
                MessageBox.Show(n);//弹出每项值
            });

 

 

posted on 2012-06-13 15:09  KimhillZhang  阅读(454)  评论(0编辑  收藏  举报