请解释.NET代表代表、NET

由网友(狗友不如狗i)分享简介:所以,我读MSDN和堆栈溢出。我明白这个动作代表做一般什么,但它不是点击,无论我有多少的例子做的。在一般情况下,同样为代表的想法。因此,这里是我的问题。当你有一个功能是这样的:So I read MSDN and Stack Overflow. I understand what the Action Delegat...

所以,我读MSDN和堆栈溢出。我明白这个动作代表做一般什么,但它不是点击,无论我有多少的例子做的。在一般情况下,同样为代表的想法。因此,这里是我的问题。当你有一个功能是这样的:

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 for the idea of delegates. So here is my question. When you have a function like this:

public GetCustomers(Action<IEnumerable<Customer>,Exception> callBack)
{
}

这是什么,什么我应该传递给它?

What is this, and what should I pass to it?

推荐答案

它需要一个函数,它IEnumerable和异常并返回void。

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

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

GetCustomers(SendExceptionToCustomers);

顺便说一句,GetCustomers的似乎是一个可怕的名字的这个功能 - 它要求一个动作,所以它更像是DoSomethingToCustomers

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

修改的回应置评

好是有道理的,所以现在为什么还要使用具有GetCustomer功能麻烦?我不能做同样的事情与你的函数,如果我只是将其重命名GetCustomer?

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?

那么,这里发生了什么是调用者可以指定一些行动。 GetCustomers的假设是这样实现的:

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

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

,那么你可以调用GetCustomers的从某处一个命令行程序,并把它传递

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);
}); 

同时,你可以从远程应用程序调用GetCustomers的,例如,并把它传递

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
})

此外,Slak的意见建议另一个原因委托参数 - GetCustomers的并检索客户,而是以异步方式。每当它完成检索客户,它调用函数你无论是customerlist或异常给它,如果发生了异常。

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.

阅读全文

相关推荐

最新文章