Why do delegates need events? Why do we even need events?

In recent weeks, I have been confused about events. I understand how delegates work, not how it works in detail, but enough to know that delegate datatypethis is one cast delegate. delegate void- This is a multicast delegate - a list of method references.

I know that the delegate type compiles into a class, but unfortunately, I still don't know how this method is referenced. for instance

delegate void TestDelegate();
TestDelegate testDelegate = new TestDelegate(myObject.SomeMethod) ;

Question 1: I think myObject is the target, and SomeMethod is a reference method, but I skip only one input. So myObject.SomeMethod compiled into a string and is a period-separated string? Funny I know.

Question 2: When do you add to the multicast delegate

multicastdelegate+=newmethodtobereference
multicastdelegate() ;

? , event? , , ? , . , , , .

using System;
namespace LambdasETs
{
    public delegate void IsEvenNumberEventHandler(int numberThatIsEven);

    public class IsEvenNumberFound
    {
        public  IsEvenNumberEventHandler IsEvenNumberEvent;
        private int number;

        public void InputNumber(int n)
        {
            if(number %2 ==0)
            {
                if (IsEvenNumberEvent != null)
                {
                    IsEvenNumberEvent(n);
                }
            }
        }


        public static void Main()
        {
            IsEvenNumberFound isEvenNumberFound = new IsEvenNumberFound();

            isEvenNumberFound.IsEvenNumberEvent += IsEvenNumberAction;

             isEvenNumberFound.InputNumber(10);

            Console.ReadLine();

        }

        public static void IsEvenNumberAction(int number)
        {
            Console.WriteLine("{0} is an even number!", number);
        }
    }


}

event public IsEvenNumberEventHandler IsEvenNumberEvent; . , , , noob .

+5
2

, , - . delegate void - - .

. "" , .

1: , myObject , SomeMethod - , . , myObject.SomeMethod , ? .

, myObject.SomeMethod - . .

multicastdelegate + = newmethodtobereference

multicastdelegate , multicastdelegate = multicastdelegate + newmethodtobereference, .. , multicastdelegate.


: ?

. . , , (+=) (-=), .

: get set.

subscribe unsubscribe, .

+2

, . , . null, , , . + = - =, .

. , , . , . , . , System.Windows.Forms.Control, EventHandlerList. WPF, EventHandlersStore.

+6

All Articles