FAQ: C # delegates and events

Source: Internet
Author: User
Keywords Dler can name understand we

I believe many people have been puzzled by C # delegates and events, especially in C # beginners, it will feel more difficult to learn this part, very likely to give up, and. NET for delegates and events encapsulation is very good, generally not how to use custom delegates and events, so give up learning the technology has an excuse!

There are a number of such articles on the web, most representative of Zhang Ziyang's C # delegates and events This article, writing is really good, get a lot of readers praise, but I read the comments, or found some problems, because there are many readers are read over and over, each feeling is fine, but at intervals, for "delegates and events" Again confused, so again to see! I really don't understand why this is happening! Later think, although the article is good, but the summary of the place did not put the focus out; Moreover, the reader followed the author's thinking, indeed can read the article, but the reader himself to no avail, did not really understand, so there is the above mentioned situation!

C # Delegates and events are really difficult, but they are not. To understand it, first of all, depends on your ability to understand; second, it depends on how you understand it. If you find it difficult to understand, then we can understand it in a different way, maybe we can understand it well! In fact, commissioned and events are not difficult, Daniel level even disdain to write such articles!

Why is there a commission?

A delegate is actually a method pointer, and any method with the same parameters and return values can be passed to the delegate, which eliminates conditional branching statements and does not need to judge which method to call based on the IF or case statements! And the delegate evolved from the Observer model, and it is recommended to read this Terrylee pattern article.

Even if you do not understand the above, it does not matter, the key is to understand the relationship between methods, delegates, events. It can be said that the method is "delegate" to the delegate, and the delegate is "delegate" to the event. You can consider an event as a container for a delegate, which can add a series of Delegates! So to understand, then all the things are solved!

Of course, we are in a method of triggering events, the event will be entrusted to the delegate, and then to the method, method and then the actual operation, and the above steps just the opposite! In fact, the purpose of triggering events is to trigger specific methods!

Again, the benefits of delegation (no examples above), for example, you developed an e-commerce platform, the backstage has the function of managing the goods, and the commodity information has seven or eight columns or more, including the number, commodity name, price, shelf time and so on, this information can be sorted according to any column! If there is no delegation, we will be based on the information generated by clicking on a column to pass this information to a sorting method, and this sort of method will accept the message as a parameter, and then according to the internal branch statements if, case, etc. to determine the specific use of the sorting method, so that logic becomes complex This process also has to do a lot of hard work (because it is likely to be a number of judgments to find the actual implementation of the method), and if we add more columns, but also to increase the branch statements, contrary to the "open-closed" principle, maintenance more trouble! With a delegate, we do not need to pass any parameters, directly to the specific method to the delegate can be added to the column just add a new method, cool! We can simply invoke the method through a delegate, so why do we need to have an event? An event is actually a restriction on a delegate so that it cannot use the "=" assignment operator (which, if used, generates an error at compile time), can only use the "+ =" or "=" operator, which prevents the programmer from accidentally overwriting the original delegate chain. In addition, the delegate class inherits from the MulticastDelegate (multicast delegate), so multiple delegates can be assigned to the same event!

Finally, make a list of code to clear up the above concepts

Class Program


{


static void Main (string] args)


{


Xiaobai Xiaobai = new Xiaobai ();


//google Company


itcompany Google = new Itcompany ("Google China", "CTO", Xiaobai);


//Microsoft company


itcompany Microsoft = new Itcompany ("Microsoft China", "architect", Xiaobai);


//Citibank


Financecompany Americabank = new Financecompany ("Citibank", "financial Analyst", Xiaobai);


//Delegate benefits can be applied to different classes of different methods


//Method "delegate" to delegate, delegate "delegate" to event

The
//delegate type is the same as the delegate type when the event is declared


//Because it is a reference, the method cannot be followed by parentheses, and parentheses is the method of invocation


//A delegate can carry multiple methods, and an event has a delegate chain


Xiaobai. Update + = new Theeventhandler (google.cometoitcompany);


Xiaobai. Update + = new Theeventhandler (microsoft.cometoitcompany);


Xiaobai. Update + = new Theeventhandler (americabank.cometofinancecompany);


Xiaobai. Subjectstate = "I small white come to apply for a position!" ";


//notification, triggering event


Xiaobai. Notify ();


//The following code is similar to the above


Xiaohua Xiaohua = new Xiaohua ();


Itcompany microsoft2 = new Itcompany ("Microsoft Corporation", "CEO", Xiaohua);


Financecompany Chinabank = new Financecompany ("China Central Bank", "finance Department general manager", Xiaohua);


Xiaohua. Update + = new Theeventhandler (microsoft2.cometoitcompany);


Xiaohua. Update + = new Theeventhandler (chinabank.cometofinancecompany);


Xiaohua. Subjectstate = "I am Xiao Hua come to apply for a position!" ";


Xiaohua. Notify ()


Console.ReadLine ();


}


}


//Notification user interface


Interface Subject


{


void Notify ();





string Subjectstate


{


get;


set;


}


}

A delegate of a
//event handler, which is equivalent to a class (indeed a class after being translated into IL) or a method pointer,


are different from regular class definitions, with parameters and return values


delegate void Theeventhandler ();


//Small white


class Xiaobai:subject


{


//Declaration event update, type as delegate Theeventhandler


public event Theeventhandler Update;


private string action; To trigger an event with the Notify Method


public void Notify ()


{


Update ();


}


public string Subjectstate


{


get {return action;}


set {action = value;}


}


}


//Xiaohua


class Xiaohua:subject


{


//Declaration event update, type as delegate Theeventhandler


public event Theeventhandler Update;


private string action;


//triggering events with the Notify Method


public void Notify ()


{


Update ();


}


public string Subjectstate


{


get {return action;}


set {action = value;}


}


}


//it Industry


class Itcompany


{


private string CompanyName;


private string Job;


private Subject Sub;





public Itcompany (String _companyname, String _job, Subject _sub)


{


companyname = _CompanyName;


job = _job;


sub = _sub;


}


//parameters and return values are consistent with the delegate Theeventhandler


public void Cometoitcompany ()


{


Console.WriteLine ("{0} {1}"): Come to our company to do {2}! ", Sub. Subjectstate,


CompanyName, Job);


}


}


//Financial industry


class Financecompany


{


private string CompanyName;


private string Job;


private Subject Sub;





public Financecompany (String _companyname, String _job, Subject _sub)


{


companyname = _CompanyName;


job = _job;


sub = _sub;


}


//parameters and return values are consistent with the delegate Theeventhandler


public void Cometofinancecompany ()


{


Console.WriteLine ("{0} {1}"): Come to our company to do {2}! ", Sub. Subjectstate,


CompanyName, Job);


}


}

Through the above summary, I believe that you should have a better understanding of C # delegates and events! Of course, the delegation of knowledge more than these, but also used to check the null value, exception handling and multithreading, and so on, this article only in the FAQ (I am also not happy to waste too much time to specific explanation)! If you want to better master the delegates and events, take a look at the two articles mentioned above, or buy a Zhang Ziyang of the C # Theory of nature, and if you want to know the observer pattern, look at the Terrylee article above; If you have not yet studied design patterns or have just begun to learn, I suggest reading Big talk design pattern; If you have been studying design patterns for some time, I suggest reading design patterns: Engineering implementation and extension based on C #! Good luck to you programmers!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.