问题描述
所以我阅读了 MSDN 和 Stack Overflow.我了解操作代表的一般作用,但无论我做了多少示例,它都不会点击.一般来说,代表的想法也是如此.所以这是我的问题.当你有这样的功能时:
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 和 Exception 并返回 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 确实检索了客户,但是是异步的.每当它完成检索客户时,如果发生异常,它会使用客户列表或异常调用您提供给它的函数.
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.
这篇关于请解释 .NET 代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!