由匿名方法到Lambda表达式的演变

发布时间 2024-01-09 15:00:13作者: 獨懼

一.具名方法

       具名方法如下Add50,实例化委托时赋值方法名称,C#中的委托像C、C++中的函数指针,保存的是方法的地址(函数指针)       

public static int Add50(int x)
{
    return x + 50;
}

// 自定义委托类型
// 注意是自定义类型
delegate int MyDel(int inParam);

static void Main()
{
    MyDel del = Add50;
    Console.WriteLine($"{del(5)}");
}

  二.匿名方法 

         不使用独立的具名方法,是实例化委托时内联(inline)声明方法     

         delegate(int x)方法声明是不具名的,只在此处引用,不再复用。

// 自定义委托类型
// 注意是自定义类型
delegate int MyDel(int inParam);

static void Main()
{
    MyDel del = Add50;
    Console.WriteLine($"{del(5)}");
}

delegate int MyDel(int inParam);

static void Main()
{
    MyDel del = delegate(int x)
    {
        return x + 50;
    }
    Console.WriteLine($"{del(5)}");
}

 三.Lambda表达式

        匿名方法的简要表示 ,以下示例是从匿名方法到Lambda表达式演变过程
  使用预定义委托类型Action或Func,可以不用自定义委托类型了
// 自定义委托类型
// 注意是自定义类型
delegate int MyDel(int inParam);

static void Main()
{
    MyDel del0 = (int x)
    {
        return x + 50;
    }

    MyDel del1 = (int x) => { return x + 50; };

    MyDel del2 = (x) => { return x + 50; };

    MyDel del3 = x => { return x + 50; };

    MyDel del4 = x => x + 50;

    // 使用预定义委托类型Action或Func
    // 注意是自定义类型
    Func<int, int> del5 = new((x) => { return x + 50; });

    Func<int, int> del6 = new(x => x + 50);

    Console.WriteLine($"{del1(0)}");
    Console.WriteLine($"{del1(1)}");
    Console.WriteLine($"{del2(2)}");
    Console.WriteLine($"{del3(3)}");
    Console.WriteLine($"{del4(4)}");
    Console.WriteLine($"{del5(5)}");
    Console.WriteLine($"{del6(6)}");
}