Whats is the difference between nested method call

2019-06-25 08:32发布

问题:

consider following:

1st APPROACH:

public void f3()
{
f2();
f1();
}

and this ...

2nd APPROACH:

    class Sample
{
    public delegate void MyDelegate(string s);
    MyDelegate obj;

    public Sample()
    {
        obj += new MyDelegate(input);
        obj+=new MyDelegate(something);
        obj += new MyDelegate(someStaticMethod);
    }
}

When i call f3() it will call the functions listed inside it ... same would happen when i will invoke a delegate ... so whats the use of delegate to handle some event when i can use 1st approach ... the 1st approach too encapsulates the method call..

回答1:

In case of the delegate, the invocation order of the attached functions is not specified.

Also, you can attach any number of functions to it, even during runtime, from other objects, not just the hard coded ones as in the first approach. The delegate has wider usage.



回答2:

First approach is static. Delegate approach allows you or a caller to determine what gets called at a later time.