Skip to content

江南小碧的C#教程:5、函数/递归/委托/匿名函数(Lambda) #23

Open
@bieberg0n

Description

@bieberg0n
Owner

函数

我们以自定义一个求绝对值的abs函数为例:

using static System.Console;

class TestAbs {
    static int abs(int x) {
        if (x >= 0) {
            return x;
        } else {
            return -x;
        }
    }

    static void Main() {
        var a = -100;
        WriteLine(abs(a));
    }
}

输出100。

递归

再来个经典的递归求斐波那契的函数:

using static System.Console;

class TestFib {
    static int Fib(int x) {
        if (x == 1) {
            return 0;
        } else if (x == 2) {
            return 1;
        } else {
            return Fib(x-1) + Fib(x-2);
        }
    }

    static void Main() {
        WriteLine(Fib(10));
    }
}

委托

委托类似于C++的函数指针,通过它可以方便地把一个方法塞到另一个方法的参数中。
参见[C#] 委托与事件(1)
另附一个Python的map函数的C#类似实现:

using static System.Console;

class Test {
    delegate void del(int i);

    static void map(del func, int[] i) {
        foreach (int j in i) {
            func(j);
        }
    }

    static void Main() {
        // del myDelegate = x => x * x;
        // WriteLine(myDelegate(5));
        int[] i = {1,2,3};
        map(WriteLine, i);
    }
}

输出

1
2
3

匿名函数

Lambda简单用法参见微软官方教程Lambda 表达式(C# 编程指南)

在上面代码的基础上,通过匿名函数快速对数组中的数进行平方:

using static System.Console;

class Test {
    delegate int del(int i);

    static void map(del func, int[] i) {
        foreach (int j in i) {
            WriteLine(func(j));
        }
    }

    static void Main() {
        del myDelegate = x => x * x;
        int[] i = {1,2,3};
        map(myDelegate, i);
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @bieberg0n

        Issue actions

          江南小碧的C#教程:5、函数/递归/委托/匿名函数(Lambda) · Issue #23 · bieberg0n/blog