// Create a normal function
void OnButtonClick()
{
MessageBox.Show("Hello World!");
}
// Now we create a delegate called ButtonClick
delegate void ButtonClick();
You see, the delegate takes the form of a normal function but without any arguments (It could take any amount of arguments just like any other method, but for the sake of simplicity, it doesn't).
现在,让我们使用我们所有的; 我们将定义委托,就像我们定义任何其他变量一样:
ButtonClick ButtonClicked = new ButtonClick(OnButtonClick);
从这里,我们可以转到 lambda 表达式,看看它们在你的情况下是否有用:
已经定义了许多委托。NET 库,有些类似于 Action,它们不接受任何参数,也不返回值。它被定义为 public delegate void Action();
You can always use it to your needs instead of the need of defining a new delegate every time. In the previous context for example, you could had just written
Action ButtonClicked = new Action(OnButtonClick);
ButtonClicked();
new Action(() => MessageBox.Show("Hello World!"))();
很抱歉我写了这么长的文章,希望不会让你太困惑:)
编辑: 我忘了提到一个替代形式,即使不经常使用,也可以使 lambda 表达式更容易理解:
new Action(delegate() {
Console.WriteLine("I am parameterless");
})();
此外,使用泛型:
// Defines a delegate that has one parameter of type string. You could pass as many parameters as you want.
new Action<string>(delegate(string x) {
Console.WriteLine(x);
})("I am a string parameter!");
// Assign C# code to the code variable.
string code = @"
using System;
namespace First
{
public class Program
{
public static void Main()
{
" +
"Console.WriteLine(\"Hello, world!\");"
+ @"
}
}
}
";
Create the provider and parameters of the compiler:
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();