且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

匿名方法的小例子

更新时间:2022-04-21 16:34:59

在 2.0 之前的 C# 版本中,声明委托的唯一方法是使用命名方法。C# 2.0 引入了匿名方法。
要将代码块传递为委托参数,创建匿名方法则是唯一的方法。

 

 /// <summary>
/// 在WindowsFrom中使用匿名函数
/// </summary>
public class TestForm : System.Windows.Forms.Form
{
        
public TestForm()
        {
            Button btn 
= new Button();
            btn.Location 
= new System.Drawing.Point(3030);
            btn.Size 
= new System.Drawing.Size(5050);
            btn.Text 
= "click me";
            btn.Click 
+= delegate(object sender, EventArgs ars)
            {
                MessageBox.Show(
"I was clicked");
            };
            Controls.Add(btn);
        }
}


    
delegate void ShowMessage(string msg);
    
/// <summary>
    
/// 匿名方法的例子
    
/// </summary>
    public class anymethod
    {
        
public void TestAnanymethod()
        {
            
string message="this is the message i want to show to user";
            ShowMessage test 
= delegate(string msg)
            {
                MessageBox.Show(msg);
            };
            test.Invoke(message);

            
string secmsg = "this is the second message show to user";
            test(secmsg);
        }
    }