在 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( 30 , 30 );
btn.Size = new System.Drawing.Size( 50 , 50 );
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);
}
}
/// 在WindowsFrom中使用匿名函数
/// </summary>
public class TestForm : System.Windows.Forms.Form
{
public TestForm()
{
Button btn = new Button();
btn.Location = new System.Drawing.Point( 30 , 30 );
btn.Size = new System.Drawing.Size( 50 , 50 );
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);
}
}