C#五、(委托的用法和为什么需要委托?)

, L i s t \color{Red}问题一、写一个函数,参数是一个List

10 L i s t 返回其中大于10的元素并装成一个List返回

这个简单呀

static List<int> Maxx(List<int> nums)
{
    List<int> a = new List<int>();
    foreach (int num in nums)
        if (num > 10) a.Add(num);
    return a;
}

L i s t \color{Red}问题二、写一个函数,参数是List

, L i s t 返回其中是偶数的数,组成一个List返回

static List<int> Maxx(List<int> nums)
{
    List<int> a = new List<int>();
    foreach (int num in nums)
        if (num % 2 ==0 ) a.Add(num);
    return a;
}

然后发现这两个函数很相似,就是这个逻辑不同而已

        if (num > 10) a.Add(num);
        if (num % 2 ==0 ) a.Add(num);

那我们利用委托,就可以把这些多个相似的函数封装成一个


. \color{Red}Ⅰ.声明委托

delegate bool most_function(int num);

其中delegate是委托的关键字

bool是委托要返回的类型(这里用于if的逻辑,所以是bool)

most_function是委托函数的名字,随便取吧


. \color{Red}Ⅱ.编写委托函数

10 下面分别用实现了大于10和返回偶数的功能

static most_function GreaterThan10 = delegate (int n) { return n > 10; };

static most_function is_even = delegate (int n) { return n%2==0 ; };

most_function可以看成数据类型

GreaterThan10可以看成变量名

后面的表达式就照着most_functoin的定义去自己写


\color{Red}三、在函数中传入编写的委托函数

, 这一步比较简单,直接看完整代码吧

class Program
{
    delegate bool most_function(int num);

    static most_function GreaterThan10 = delegate (int n) { return n > 10; };

    static most_function is_even = delegate (int n) { return n%2==0 ; };
    static List<int> Maxx(List<int> nums,most_function S)
    {
        List<int> a = new List<int>();
        foreach (int num in nums)
            if ( S(num) ) a.Add(num);
        return a;
    }
    static void Main(string[] args)
    {
        List<int> a = new List<int>() { 1, 2, 3, 999, -1, 4,11 };
        a = Maxx(a,is_even);
        foreach (int num in a)
            Console.WriteLine(num);
    }
}

我的理解就是委托的功能之一就是

, 能封装函数,并作为参数传进函数中去

再看一下我们写的委托函数以及调用代码

static most_function is_even = delegate (int n) { return n%2==0 ; };
List<int> a = new List<int>() { 1, 2, 3, 999, -1, 4,11 };
a = Maxx(a,is_even);

使 l a m b d a 实际上使用lambda表达式更简洁

 List<int> a = new List<int>() { 1, 2, 3, 999, -1, 4,11 };
 a = Maxx(a, (n) => { return n % 2 == 0; });

()内是委托函数的参数

{}内是函数的语句

其实还是在构造这个委托函数,不过简化了一些

猜你喜欢

转载自blog.csdn.net/jziwjxjd/article/details/107291795