Imagine a scenario in which you have a function that searches a Customer. Initially you just want to search by name so you write something like:
public Customer Find(string name)
{
foreach (var customer in database.Customers)
if (customer.Name == name)
return customer;
}
Then your specifications change and you have to implement new ways of searching (let's say "search-by-address"). No problem, we refactor our old code to:
public Customer FindByName(string name)
{
foreach (var customer in database.Customers)
if (customer.Name == name)
return customer;
}
public Customer FindByAddress(string address)
{
foreach (var customer in database.Customers)
if (customer.Address == address)
return customer;
}
They look very similar, don't they?
Now your boss tell again you to add another search functionality, the user may want to find customers by telephone number. It is getting boring, isn't it?
Fortunately developers have found a way to make other developers' life easier inventing delegates. Using them you could create one bigger, general function that helps you to avoid rewriting the same pieces of code again and again.
public Customer Find(Predicate<Customer> p)
{
foreach (var customer in database.Customers)
if (p(customer))
return customer;
}
Now you do not have to create a specialized function each time you need a new way of searching customers, so you can write:
var byName = Find(a => a.Name == "lorem");
var byAddress = Find(a => a.Address == "ipsum");
var byTelephone = Find(a => a.Telephone == "dolor");
Delegates are also useful to manage events and are used intensively also in LINQ. Just google "delegates c#" and you will discover a huge new world! :)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…