Please Explain .NET Delegates

前端 未结 9 1219
离开以前
离开以前 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:28

    A delegate is a class that points to one or more functions. A delegate instance can be invoked, which will call the function(s) that it points to.

    In your case, the GetCustomers function takes a second function as a parameter.

    The second function must take two parameters of type IEnumerable and Exception.

    To call GetCustomers, you need to make a second function for it to call, then pass it a delegate containing the second function.

    For example:

    static void GetCustomersCallback(IEnumerable customers, Exception ex) {
        //Do something...
    }
    
    //Elsewhere:
    GetCustomers(new Action,Exception>(GetCustomersCallback));
    

    This call creates a new delegate instance that points to the GetCustomersCallback function, and passes that delegate to the GetCustomers function. GetCustomers will presumably call the callback after the customers finish loading, and will pass the loaded customers as a parameter.
    You can also leave out the delegate instantiation and pass the function directly:

    GetCustomers(GetCustomersCallback);
    

提交回复
热议问题