zoukankan      html  css  js  c++  java
  • C#中的函数、委托与lanbda表达式

    以下几个例子(两个整数相加): 

    (1)        int sum1(int x, int y) { return x + y; }

     

    (2)        delegate int fsum(int x, int y);

    (3)        fsum sum2 = (x, y) => x + y;

     

    (4)        int sum3(int x, int y)=(x,y)=>x+y;

    (5)        int sum4(int x, int y)=x+y; 

    (1)是c系列中定义函数的经典写法。

    (2),(3)引入委托类型

     在使用中(1)中的函数和(3)中的委托,没有多大差别,好像是一个东东一样。

    (4),(5)不能通过编译 ,其中(5)是对(4)的简化。

    加上匿名函数,匿名委托的概念,对于非软件开发专业的消费者是挺费解的。

     其实可以把委托与函数统一起来,只有复杂逻辑的函数定义,才需要使用(1)形式。简短函数使用(5)这种形式就够了。

    不知以后C#会不会加入函数定义的简化形式。 

     下面是相同形式的连乘的形式:

            static int Mul1(params int[] X) { return X.Aggregate((x, y) => x * y); }

     

            delegate int fMum(params int[] X);

            static fMum Mul2 = X => X.Aggregate((x, y) => x * y);

     

            int Mul3(params int[] X)=X=> X.Aggregate((x,y)=>x*y);

            int Mul4(params int[] X)= X.Aggregate((x,y)=>x*y);

    后面附两个例子:

    public Func<int, int> Fibonacci = n => n < 1 ?1: Fibonacci(n - 1) + Fibonacci(n - 2);

    public static Complex Add(Complex c1, Complex c2)

    = 

    {    

         Complex result = new Complex();

         result.X = c1.X+c2.X;

         result.Y = c2.Y+c2.Y;

        return result;

    }

    public static Complex Add(Complex c1, Complex c2)=

    {

        Complex result = new Complex(X=c1.X+c2.X,Y=c1.Y+c2.Y);

        return result;

    }

    public static Complex Add(Complex c1, Complex c2)= new Complex(X=c1.X+c2.X,Y=c1.Y+c2.Y);  

  • 相关阅读:
    mysql实战45讲
    goland破解
    主从复制系列C
    主从复制系列B
    主从复制系列A
    sshd配置文件详解
    MySQL源码 数据结构array
    MySQL源码 information_schema新增表
    MySQL5.6 基于db的并行复制
    mysql 限制并发select patch
  • 原文地址:https://www.cnblogs.com/xiexiaokui/p/2084564.html
Copyright © 2011-2022 走看看