开发者

C# Question: Delegates

I've been searching the Web, including MSDN.com fo开发者_如何学编程r a easy-to-understand explanation of delegates in c#. There's plenty of tutorials/lessons...but its a hard concept for me to grasp. So i thought I'd ask fellow programmers. Can anyone explain?


Delegates are like function pointers.

Take a look at this

using System;

namespace Akadia.BasicDelegate
{
    // Declaration
    public delegate void SimpleDelegate();

    class TestDelegate
    {
        public static void MyFunc()
        {
            Console.WriteLine("I was called by delegate ...");
        }

        public static void Main()
        {
            // Instantiation-- we set this simpleDelegate to MyFunc
            SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);

            // Invocation-- MyFunc is called. 
            simpleDelegate();
        }
    }
}

So what happens is that when you call simpleDelegate, MyFunc is called instead, because simpleDelegate is pointing to MyFunc.

In the case of doubt, you should copy the above code, paste it inside your VS, and run your debugger through it. Examine how the program flows from one place to another; see for yourself after simpleDelegate() line is called, the program jumps to MyFunc and executes from there. Examine the simpleDelegate variable, see that it contains a reference to MyFunc the method. This would be the best way for you to get familiar with the whole delegate thing.


Basically a delegate runs any number of methods you subscribe to it. They must match the parameters and the return type (this is called "signature"), that is, if your delegate takes two ints and returns a void:

public delegate void MyDelegate(int i1, int i2);

The methods you subscribe to it must take two strings and return a void too:

public void Add(int int1, int int2)
{
    MessageBox.Show((int1 + int2).ToString());
}

public void Multiply(int int1, int int2)
{
    MessageBox.Show((int1 * int2).ToString());
}

And now subscribe, run and see the results:

public void SubscribeAndRun()
{
    MyDelegate d = new MyDelegate(Add);

    d += Multiply;

    d.Invoke(2, 3);
}

Delegates are extensively used to call other methods when an event happens. In C# events are delegates encapsulated to use add and remove (to add or remove the methods the event will run when it fires).


For a good tutorial, please see Delegates:

A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value, as in this example:


Here's a simple example

using System;

namespace delegates
{
    class Program
    {
        // An event which you set up by attaching handlers (delegates)
        // and then running using the Invoke() method.
        private EventHandler<EventArgs> _event;

        void SetupFoo()
        {
            // Attach the function foo to the _event
            _event += Foo;
        }

        void SetupBar()
        {
            // Attach a delegate (aka anonymous method) to the _event
            _event += delegate { Console.WriteLine("Bar is called"); };
        }

        void SetupBaz()
        {
            // Attach a lambda to the _event
            _event += (sender, e) => Console.WriteLine("Baz is called");
        }

        void Fire()
        {
            // Run all the attached methods/delegates/lambdas
            _event.Invoke(this, EventArgs.Empty); 
        }


        static void Main(string[] args)
        {
            var prog = new Program();
            prog.SetupFoo();
            prog.SetupBar();
            prog.SetupBaz();
            prog.Fire();
            Console.ReadKey();
        }

        private static void Foo(object sender, EventArgs e)
        {
            Console.WriteLine("Foo is called");
        }
    }
}

This produces the output:

Foo is called
Bar is called
Baz is called

Why are delegates important? Because Fire() was responsible only for the timing of the event execution, but other functions were responsible for the consequences of the event. These consequences are expressed as delegates.


Think Functors. i.e. a function that can be handled sort of like an object (i.e. a pointer)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜