Please Explain .NET Delegates

前端 未结 9 1221
离开以前
离开以前 2020-12-30 07:40

So I read MSDN and Stack Overflow. I understand what the Action Delegate does in general but it is not clicking no matter how many examples I do. In general, the same goes f

9条回答
  •  无人及你
    2020-12-30 08:23

    it expects a function that takes IEnumerable and Exception and returns void.

    void SendExceptionToCustomers(IEnumerable customers, Exception ex) {
       foreach(var customer in customers)
          customer.SendMessage(ex.Message);
    }
    
    GetCustomers(SendExceptionToCustomers);
    

    btw, GetCustomers seems like a terrible name for this function -- it's asking for an action, so its more like DoSomethingToCustomers

    EDIT in response to comment


    Ok Makes sense, So now why even bother with having a GetCustomer Function? Can't I do that same thing with your function if i Just rename it GetCustomer?

    Well, what's happening here is the caller can specify some action. Suppose GetCustomers is implemented like this:

    public void GetCustomers(Action, Exception> handleError) {
        Customer[] customerlist =  GetCustomersFromDatabase();
        try {
            foreach(var c in customerList) 
                c.ProcessSomething()
        } catch (Exception e) {
            handleError(customerList, e);
        }
    }
    

    then you could call Getcustomers from somewhere on a commandline program, and pass it

    GetCustomers((list, exception) => { 
        Console.WriteLine("Encountered error processing the following customers");
        foreach(var customer in list) Console.WriteLine(customer.Name);
        Console.WriteLine(exception.Message);
    }); 
    

    while you could call GetCustomers from a remote application, for example, and pass it

    Getcustomers((list, exception) => { 
        // code that emails me the exception message and customer list
    })
    


    Also, Slak's comment suggests another reason for delegate parameter -- GetCustomers does retrieve the customers, but asynchronously. Whenever it is done retrieving the customers, it calls the function you give it with either the customerlist or an exception, if an exception occurred.

提交回复
热议问题