简体   繁体   中英

Referencing multiple methods using one delegate

I'm currently sandpitting delegates.
In the following example does dd reference pm and pn ?
Can I add another line to run pm again after adding pn ? Or do I need to implement d dd = pm; 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
//is there now a quick way to run p.m ?

是的,除了daryal的帖子,这可以通过以下方式完成(同时仍然维护多播委托):

p.GetInvocationList()[0].DynamicInvoke(new object[] { 3 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM