简体   繁体   中英

Need help using c# delegate function

delegate bool Function(int num);
static Function GreatThan10 = delegate(int n){return n >= 10; };    //there is error  

class Program
{

    static List<int> Traverse(List<int> myList, Function function)
    {
        var list = new List<int>();
        foreach (var item in myList)
        {
            if (function(item))
            {
                list.Add(item);
            }

        }
        return list;
    }       

When I use c# delegate, I find there is an error. Also I want to know its delegate whether is the same as php callback function?

I am just learning c# and feel its resource relatively litter than JAVA. I want to learn deeply with books.Are there good books can recommend to me?

Your delegate declaration just shows the shape that a function would have to have in order to qualify as an input wherever a Function exists. You don't have to declare the Function itself as a delegate. It can just be an ordinary Function:

static bool GreatThan10(int n) 
{ 
    return n >= 10; 
}

Then you can pass it as an argument to Traverse, for example:

var bigNumbers = Traverse(new List<int> {1, 10, 100}, GreatThan10);

You just have to move the GreatThan10 field inside your class Program. The first line of your code is just to define a new delegate that takes an int parameter and returns a bool. The GreatThan10 instead is a reference of that delegate type, so it must be a member of a class.

You also asked if a delegate is the same as PHP callback functions. I would say that a delegate is a type that represents a reference to methods. You declare it with some parameters and with a return type, and you can then create new references of that delegate that points to some methods with the same parameters type and return type.

Try this solution and you should not have any problems.

using System;
using System.Collections.Generic;

delegate bool Function(int n);

class Program
{
    static Function GreatThan10 = delegate(int n) { return n > 10; };

    static void Main(string[] args)
    {
        List<int> list = new List<int>();

        Traverse(list, GreatThan10);

        Console.ReadKey();
    }

    static List<int> Traverse(List<int> myList, Function function)
    {
        var list = new List<int>();
        foreach (var item in myList)
        {
            if (function(item))
            {
                list.Add(item);
            }

        }
        return list;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM