C # - Understanding events, eventhandlers and delegates [duplicated]

3

I have to know if I have clear 4 points that I will explain:

1- A delegate is a type of data that is created in order to store method addresses (to be called later) with a specific signature. Is this correct?

2-An event is declared in a delegate to get to call a method when necessary, in certain cases a lambda = > to indicate a block to execute or a method Is this correct?

3- The code below can be seen as I create a delegate, which according to me is well created and correctly pointing to a method, then on the line where are the %%%%%% I want to know how to execute the method of delegate and when it is executed the event in question is triggered, by means of the lambda expression, resulting in the output "message", "hello"

4-What are the differences between an event and an eventhandler that have a relation between them?

 class Program
{
    static void Main(string[] args)
    {


        delegado.direccion_msj = delegado.msj;
        delegado.direccion_msj();
        delegado.direccion_msj += () => eventos.hola_delegado;%%%%%%%%



        Console.ReadKey();

    }

}

class delegado
{
    public delegate void dir_msj();

    public static dir_msj direccion_msj;



    public static void msj()
    {
        Console.WriteLine("mensaje");
        Thread.Sleep(3000);

        Console.WriteLine();


    }

}
class eventos
{


    public static void hola()
    {
        Console.WriteLine("Hola");
    }
    public delegate void eventhanhola();
    public static event eventhanhola hola_delegado = hola;
}

}

    
asked by Shiki 04.08.2017 в 04:32
source

1 answer

3
  

1- A delegate is a type of data that is created for the purpose of storing   addresses of methods (to be later called) with a signature   specifies Is this correct?

Yes. See how the following example executes both methods that are added to the delegate invoking list Mensaje thanks to the operator += :

    public delegate void Mensaje();

    class Program
    {

        public static void MensajeIngles()
        {
            Console.WriteLine("Hello World");
        }

        public static void MensajeEspanol()
        {
            Console.WriteLine("Hola mundo");
        }


        public static void Main()
        {
            Mensaje m = MensajeEspanol;
            m += MensajeIngles;

            m();

            Console.ReadLine();
        }
    }

.Net Fiddle

  

2-An event is declared in a delegate to get to call a method   When necessary, in some cases you can use an expression   lambda = > to indicate a block to execute or a method. This is   correct?

Yes. Animos (lambdas) methods that comply with the same subject as the delegate can be added to the invoking list:

    public delegate void Mensaje();

    class Program
    {
       //..
        public static void Main()
        {
            Mensaje m = MensajeEspanol;
            m += MensajeIngles;
            m += () => 555; // invalido, la signatura de la lambda es Func<int>
            m += () => Console.WriteLine("lenguaje desconocido"); // valido, la lambda iguala la asignatura del delegado
            m();

            Console.ReadLine();
        }
    }
  

3- The code below can be seen as I think a delegate, that   according to me it is well created and correctly pointing to a method,   then on the line count are the %%%%%% I want to know how to execute   the delegate's method and when it is executed the event is triggered   in question, by means of the lambda expression, resulting in   output "message", "hello"

The subject of the delegate and the labda are different. When you do () => eventos.hola_delegado; you are actually assigned a method that does not receive a parameter and that returns another method with return type void .

In other words, this:

 () => eventos.hola_delegado; 

It is equal to:

Func<Action> metodoAnomino();

But the signature that the delegate waits is void metodo(); .

Update:

If you want to print "Hello" and "message" you have to add the eventos.hola() method to the invocation list

   delegado.direccion_msj = delegado.msj;
   delegado.direccion_msj += eventos.hola;
   delegado.direccion_msj();

It is not valid to be able to add an event to a delegate's invoking list:

m += eventos.hola_delegado; // ERROR, no se puede asignar un evento a un delegado

Why can not you add an event to a delegate's invoking list? This brings us to the next question:

  

4-What are the differences between an event and an eventhandler?   Do they have each other?

A EventHandler is a delegate that does not pass data from the event that invoked it. Whereas event is a reserved key that creates an abstraction layer for the delegates, protecting them from external modification. For example, in the delegate we created, if we did this:

    Mensaje m = MensajeEspanol;
    m += MensajeIngles;
    m += () => { Console.WriteLine("lenguaje desconocido"); };
    m = () => { Console.WriteLine("lenguaje desconocido 2"); };

We would be writing the entire invoking list and we would only execute one method that would be the last one. While in event this operator is not available so you can only subscribe / unsubscribe from the invoking list which makes it more secure.

    
answered by 04.08.2017 в 05:42