I'm currently sandpitting delegates.
In the following example does dd reference p.m and p.n ?
Can I add another line to run p.m again after adding p.n ? Or do I need to implement d dd = p.m; again?
class Program
{
private delegate int d(int x);
static void Main(string[] args)
{
Program p;
p = new Program();
d dd = p.m;//d dd = new d(p.m);
Console.WriteLine(dd(3).ToString());
dd += p.n;//dd += new d(p.n);
Console.WriteLine(dd(3).ToString());
//<<is there now a quick way to run p.m ?
Console.WriteLine("press [enter] to exit");
Console.ReadLine();
}
private int m(int y)
{
return y * y;
}
private int n(int y)
{
return y * y - 10;
}
}
yes, after first assignment (d dd = this.m;), all assignment made using += will also be called.
You may just remove a method, using -=, refer to the following sample;
d dd = p.m;//d dd = new d(p.m);
Console.WriteLine(dd(3).ToString()); //calls p.m
dd += p.n;//dd += new d(p.n);
Console.WriteLine(dd(3).ToString()); //calls boths p.m and p.n
dd -= p.n;
Console.WriteLine(dd(3).ToString()); // only calls p.m
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With