Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...