Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

c# - Delegate Methods vs General Methods

I want to know the difference between using Delegate Methods and using General Methods[without Delegates].

For Example :


With Delegate :

delegate void DelMethod(string str);

static void Method(string str)
{
    Debug.WriteLine(str);
}

Usage :

DelMethod dm = new DelMethod(Method);
dm(string);

And Without Delegate :

static void Method(string str)
{
    Debug.WriteLine(str);
}

Usage :

Method(string)

What are the differences of these two??

The method without delegate is smaller and easy. But I find coders using delegated Methods frequently.

What is the reason behind this??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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! :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...