यह एक समारोह है कि IEnumerable लेता है और अपवाद और शून्य रिटर्न की उम्मीद है।
void SendExceptionToCustomers(IEnumerable<Customer> customers, Exception ex) {
foreach(var customer in customers)
customer.SendMessage(ex.Message);
}
GetCustomers(SendExceptionToCustomers);
btw, GetCustomers इस कार्य के लिए एक भयानक नाम की तरह लगता है - यह एक कार्रवाई के लिए पूछ रहा है, इसलिए इसकी अधिक DoSomethingToCustomers
तरह
जवाब में संपादित टिप्पणी करने के लिए
ठीक है समझ में आता है, तो अब GetCustomer फ़ंक्शन होने से भी परेशान क्यों है? क्या मैं अपने काम के साथ वही काम नहीं कर सकता अगर मैं इसे सिर्फ GetCustomer का नाम बदलूं?
ठीक है, यहां क्या हो रहा है कॉलर कुछ क्रिया निर्दिष्ट कर सकता है।मान लीजिए GetCustomers इस तरह कार्यान्वित किया जाता है:
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 कहते हैं, और पारित यह
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 कह सकते हैं, उदाहरण के लिए कर सकता है, और पारित यह
Getcustomers((list, exception) => {
// code that emails me the exception message and customer list
})
इसके अलावा, Slak की टिप्पणी प्रतिनिधि पैरामीटर के लिए एक और कारण पता चलता है - GetCusto mers ग्राहकों को पुनः प्राप्त करता है, लेकिन असीमित रूप से। जब भी यह ग्राहकों को पुनर्प्राप्त किया जाता है, तो यह एक ऐसा अपवाद होता है जब आप इसे किसी भी अपवाद के साथ प्राप्त करते हैं, तो आप इसे ग्राहक सूची या अपवाद के साथ देते हैं।
public void DoSomeStuffWithCustomers(
IEnumerable<Customer> customers, Exception exception)
{
}
आप इस तरह GetCustomers विधि कहेंगे:
में देख सकते हैं बुरे नाम से सहमत हैं। –
ऐसा लगता है कि कॉलबैक उन ग्राहकों को प्राप्त करता है जो ग्राहकों को असीमित रूप से लोड करने के बाद लोड (या अपवाद) प्राप्त होते हैं। – SLaks
मुझे ज्यादातर समय ग्राहकों को कुछ करना अच्छा लगेगा, खासकर जब वे परेशान हों। –