1.匿名函数定义:提供了一种传递代码块作为委托参数的技术。匿名方法是没有名称只有主体的方法。
class Program
{
delegate void Del(string str,int i);
static void Main(string[] args)
{
Del del = delegate (string str, int i)
{
Console.WriteLine(str+"的年龄是"+i);
};
del("小明", 22);
Console.ReadLine();
}
}
系统委托使用匿名函数:
static void Main(string[] args)
{
Action<string, int> Act = delegate (string str, int i)
{
Console.WriteLine(str + "的年龄是:" + i);
};
Act("小明", 22);
Func<string, int, string> func = delegate (string str, int i)
{
return str+"的年龄是:"+i;
};
Console.WriteLine(func("小明",22));
Console.ReadLine();
}
}
2.Lambda定义:一种可用于创建委托或表达式目录树类型的匿名函数。通过使用lambda表达式,可以写入可作为参数传递或作为函数调用值返回的本地函数。
static void Main(string[] args)
{
Action<string> act = str =>
{
Console.WriteLine(str + "有参");
};
act("Lambda");
Func<int, string> func = i =>
{
return "输入的数字是:" + i;
};
Console.WriteLine(func(100));
Console.ReadLine();
}