DELEGATES
* CLR's eventing model is based on delegates.
* DELEGATE is a type-safe way to invoke a callback method.
* They are just function pointers, That is, they hold references to functions.
* A Delegate is a class. When you create an instance of it, you pass in the function name (as a parameter for the delegate's constructor) to which this delegate will refer.
* Delegates also intergrate the ability to call multiple methods serially and support the calling of static methods as well as instance methods.
*All delegate types are derived from MulticastDelegate which itself is derived from System.Delegate class which itself is derived from System.Object.
* The implementation of Equals compares two delegate objects to see whether their target is same or not.
class classdelg
{static int i=1;
public delegate void del(int a, string b);
public void delfunc(del d)
{
if (d != null)
d(i++, "success");
}
}
class funcdelg
{
public void outfunc(int a, string B)
{
Console.WriteLine("OUTFUNC {0},{1}",a,B);
}
}
class p1isas
{
static void infunc(int a, string b) //not a public function
{
Console.WriteLine("INFUNC {0},{1}", a, b);
}
static void Main()
{
classdelg cd = new classdelg();
funcdelg fd= new funcdelg();
classdelg.del d = null; //delegates are type property
d += new classdelg.del(infunc);
d += new classdelg.del(fd.outfunc);
cd.delfunc(d);
Console.Read();
}
}
Delegate Chains -
Feedback fb1 =new Feedback(Func1);
Feedback fb2= new Feedback(Func2);
Feedback fbchain= (Feedback) Delegate.Combine(fb1,fb2);
fb2 function will get invoke first.
EVENTS
* Event programming model that is popular in asynchronous programming.
* Delegate usefulness does not just lie in the fact that it can hold the references to functions but in the fact that it can define and use function names at runtime and not at compile time. A large goal of design delegates is their applicability in events model of .Net
Removing Delegates
Feedback fb1 =new Feedback(Func1);
Feedback fb2= new Feedback(Func2);
Feedback fbchain= (Feedback) Delegate.Combine(fb1,fb2);
Feedback fbchain= (Feedback) Delegate.Remove(fbchain, new Feedback(Func2) );
C# provides overloads of the += and -= for Delegate.Combine and Delegate.Remove
Friday, December 19, 2008
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment