开发者

Super simple example for a Delegate-Event in c#.net? [closed]

Closed. This question does not meet St开发者_开发百科ack Overflow guidelines. It is not currently accepting answers.

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

Closed 3 years ago.

Improve this question

I need a very simple example to understand myself about the events.I am feeling very difficult to understand the examples available in internet or books.


This is a simple implementation of a class that exposes an event.

public class ChangeNotifier
{
    // Local data
    private int num; 

    // Ctor to assign data
    public ChangeNotifier(int number) { this.num = number; } 

     // The event that can be subscribed to
    public event EventHandler NumberChanged;

    public int Number
    {
        get { return this.num; }
        set
        {
            // If the value has changed...
            if (this.num != value) 
            {
                // Assign the new value to private storage
                this.num = value;

                // And raise the event
                if (this.NumberChanged != null)
                    this.NumberChanged(this, EventArgs.Empty);
            }
        }
    }
}

This class may be used something like as follows:

public void SomeMethod()
{
    ChangeNotifier notifier = new ChangeNotifier(10);

    // Subscribe to the event and output the number when it fires.
    notifier.NumberChanged += (s, e) => Console.Writeline(notifier.Number.ToString());

    notifier.Number = 10; // Does nothing, this is the same value
    notifier.Number = 20; // Outputs "20" because the event is raised and the lambda runs.
}

Regarding control flow, execution flows into SomeMethod(). We create a new ChangeNotifier and thus call its constructor. This assigns the value of 10 to the private num member.

We then subscribe to the event using the += syntax. This operator takes a delegate on the right hand side (in our case, that delegate is a lambda) and adds it to the collection of delegates on the event. This operation doesn't execute any code that we've written in the ChangeNotifier. It can be customized through the add and remove methods on the event if you'd like, but there's rarely a need to do that.

Then we perform a couple simple operations on the Number property. First we assign 10, which runs the set method on the Number property with value = 10. But the num member is already valued at 10, so the initial conditional evaluates to false and nothing happens.

Then we do the same thing with 20. This time the value is different, so we assign the new value to num and fire the event. First we verify that the event is not null. It's null if nothing has subscribed to it. If it's not null (ie, if something is subscribed to it), we fire it using the standard method/delegate syntax. we simply call the event with the event's arguments. This will call all methods that have subscribed to the event, including our lambda that will perform a Console.WriteLine().


Henrik has successfully nitpicked the potential race condition that exists if one thread can be in Number's setter while another thread is unsubscribing a listener. I don't consider that a common case for someone who doesn't yet understand how events work, but if you're concerned about that possibility, modify these lines:

if (this.NumberChanged != null)
    this.NumberChanged(this, EventArgs.Empty);

to be something like this:

var tmp = this.NumberChanged;
if (tmp != null)
    tmp(this, EventArgs.Empty);


class Program
    {
        static void Main(string[] args)
        {
            Parent p = new Parent();
        }
    }

    ////////////////////////////////////////////

    public delegate void DelegateName(string data);

    class Child
    {
        public event DelegateName delegateName;

        public void call()
        {
            delegateName("Narottam");
        }
    }

    ///////////////////////////////////////////

    class Parent
    {
        public Parent()
        {
            Child c = new Child();
            c.delegateName += new DelegateName(print);
            //or like this
            //c.delegateName += print;
            c.call();
        }

        public void print(string name)
        {
            Console.WriteLine("yes we got the name : " + name);
        }
    }


Class A {
    public delegate void EventHandler();

    public static event EventHandler workComplete();

    void doWork(){
        // DO WORK  
    }

    void onWorkComplete(){
        // Raise event
        workComplete();
    }
}

Class Main {
    A a = new A();
    a.workComplete += new () -> {
        // On Class Complete Work
        Console.WriteLine("Work Complete");
    };
}


If you have C background, you can see delegate as a pointer to function.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜