开发者

where to use delegates in c#

i have better understanding in how the delegates and events work , but i dont know where it is of full use when we develop a Library or a application.

t开发者_JAVA百科hanks


Delegates are significant as they are needed to work with events (not just this).

Lets say we have a winform F1..A function within F1 opens another form F2. and if a function within F1 has to be executed based on users activity on F2 we'll definitely have to make use of delegates and events.

1)A delegate type has to be declared (Signature has to match with eventhandler which you are planning to attach) 2)F2 will need to have an event as class member of delegate type 3)Just as you create an instance of F2 in F1 , attach the event handler (using += )


Delegates are similar to function pointers of C/C++ but are of class type and not primitive type. The basic use of delegates is to perform some call back or asynchronous methods or to pass different methods at runtime. (substituting the logic)

Example for performing asynchronous call back. It is more appropriate when you have multiple threads running.

public class MyClass {

public delegate void CallBackDelegate(int result); public void CallsBack(CallBackDelegate callBack) { // your code here - do something useful callBack(result); }

}

public class DelegateExample { // some more useful code here void ExampleMethod() { // more code MyClass myclass = new MyClass(); myclass.CallsBack(CallMeBack); // Continue with your work and don't wait for call back. } void CallMeBack(int result) { // do something useful } }


This is a very general question, but a typical use of delegates and events would be in a GUI library. For example, you could set up events to fire when a button is clicked on an application, or when a value is changed in a field, and a developer could then use delegates to specify one of their own functions to be called in response to that button click, or to perform validation on the changed data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜