匿名函数学习笔记(一)

匿名函数的定义:匿名函数是一个“内联”语句或表达式,可在需要委托类型的任何地方使用。可以使用匿名函数来初始化命名委托,或传递命名委托(而不是命名委托类型)作为方法参数。

匿名函数一个分两种:一种是Lambda表达式,另一种是匿名方法。

现在的匿名函数已经由C# 1.0发展到了C# 3.0了。而匿名方法的概念是在C# 2.0中引入的,Lambda表达式则是在C# 3.0中引入。

下面的示例演示了从 C# 1.0 到 C# 3.0 委托创建过程的发展(摘自msdn):

 

class Test
{
    delegate void TestDelegate(string s);
    static void M(string s)
    {
        Console.WriteLine(s);
    }

    static void Main(string[] args)
    {
        // Original delegate syntax required 
        // initialization with a named method.
        TestDelegate testDelA = new TestDelegate(M);

        // C# 2.0: A delegate can be initialized with
        // inline code, called an "anonymous method." This
        // method takes a string as an input parameter.
        TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };

        // C# 3.0. A delegate can be initialized with
        // a lambda expression. The lambda also takes a string
        // as an input parameter (x). The type of x is inferred by the compiler.
        TestDelegate testDelC = (x) => { Console.WriteLine(x); };

        // Invoke the delegates.
        testDelA("Hello. My name is M and I write lines.");
        testDelB("That's nothing. I'm anonymous and ");
        testDelC("I'm a famous author.");

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
    Hello. My name is M and I write lines.
    That's nothing. I'm anonymous and
    I'm a famous author.
    Press any key to exit.
 */

Lambda表达式使用的运算符为  =>

运算符的左边是输入参数,而右边是表达式或语句块。

示例如下(摘自msdn):

delegate int del(int i);
static void Main(string[] args)
{
    del myDelegate = x => x * x;
    int j = myDelegate(5); //j = 25
}

Lambda 表达式返回表达式的结果

//基本形式:
(input parameters) => expression
//只有在 Lambda 有一个输入参数时,括号才是可选的;否则括号是必需的。 两个或更多输入参数由括在括号中的逗号分隔:
(x, y) => x == y
//有时,编译器难于或无法推断输入类型。 如果出现这种情况,您可以按以下示例中所示方式显式指定类型:
(int x, string s) => s.Length > x
//使用空括号指定零个输入参数:
() => SomeMethod()

Lambda 语句与 Lambda 表达式类似,只是语句括在大括号中,在此就不累述了。

我对其表达式的理解就是:

  • 果汁 = 水果 =>  榨汁机

我们想要一杯果汁,这杯果汁可能是苹果汁,也可能是柳橙汁。而我们给的水果,便是一个参数,这个参数可以使苹果,也可以使橙子。榨汁机就是那个表达式或语句块。

  • 注意:=> 运算符具有与赋值运算符 (=) 相同的优先级,并且是右结合运算符。

转载于:https://www.cnblogs.com/stevezheng/archive/2011/09/17/2179625.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值