Events and delegates versus calling methods

Hopefully this issue will not be closely related to others, but others do not seem to fill the knowledge gap.

This seems to be a hot topic to try to understand events and delegates, and after reading many SO questions and MSDN articles, I'm afraid to say that I still don't understand. After a few years creating great web applications, I found myself very upset not understanding them. Please can someone clarify this in the generic code. So the question is: why use events and delegates to call a method?

Below is some basic code that I wrote at work. Will I be able to use events and delegates?

Public Class Email
{
   public string To {get;set;}
   //Omitted code

   public void Send()
   {
    //Omitted code that sends.
   }
}

Public Class SomeClass
{
   //Some props

   Public void DoWork()
  {
    //Code that does some magic

    //Now Send Email
    Email newEmail = new Email();
    newEmail.To = "me@me.com";
    newEmail.Send();
  }
}

, , , , DoWork() ? ? - .

,

+4
5

, , - , .

, " ". , , . .

" " , .

, , Logger, . LogEvent(string desc, DateTime time) :

public class Logger 
{
  ...
  public void LogEvent(string desc, DateTime time)
  {
    ...//some sort of logging happens here
  }
}

, Email class 'Send, Logger LogEvent:

public void Send()
   {
    //Omitted code that sends.
    var logger = new Logger();
    logger.LogEvent("Sent message", DateTime.Now);
   }

Email Logger. LogEvent Logger, Email. , , ? , LogEvent, , - , , ​​ . , , , , "" . , , , , , .

Email , :

Public Class Email
{
   public event EventHandler<EventArgs> Sent;
   private void OnSent(EventArgs e)
    {
        if (Sent!= null)
            Sent(this, e);
    }

   public string To {get;set;}
   //Omitted code

   public void Send()
   {
    //Omitted code that sends.
    OnSent(new EventArgs());//raise the event
   }
}

Logger Email.Sent , :

public class Logger 
{
  ...
  public void Email_OnSent(object sender, EventArgs e)
  {
    LogEvent("Message Sent", DateTime.Now);
  }

  public void LogEvent(string desc, DateTime time)
  {
    ...//some sort of logging happens here
  }
}

:

var logger = new Logger();
var email = new Email();

email.Sent += logger.Email_OnSent;//subscribe to the event

, , , Logger - , , LogEvent Email. , , Email, , .

, , , 20 , , - .

BIG EDIT: . : - : # ( , ), , . (.. (object sender, EventArgs e)) , (+=), . , , . , ?

, Email . :

Public Class Email
{
   public string To {get;set;}
   //Omitted code

   public void Send(MailMethod method)
   {
     switch(method)
     {
       case MailMethod.Imap:
         ViaImap();
         break;
       case MailMethod.Pop:
         ViaPop();
         break;
      }
   }

   private void ViaImap() {...}

   private void ViaPop() {...}
}

, , ( MailMethod, ). , :

Public Class Email
{
   public Email()
   {
     Method = ViaPop;//declare the default method on instantiation
   }

   //define the delegate
   public delegate void SendMailMethod(string title, string message);

   //declare a variable of type SendMailMethod
   public SendMailMethod Method;

   public string To {get;set;}
   //Omitted code

   public void Send()
   {
     //assume title and message strings have been determined already
     Method(title, message);
   }

   public void SetToPop()
   {
     this.Method = ViaPop;
   }

   public void SetToImap()
   {
     this.Method = ViaImap;
   }

   //You can write some default methods that you forsee being needed
   private void ViaImap(string title, string message) {...}

   private void ViaPop(string title, string message) {...}
}

, :

var regularEmail = new Email();
regularEmail.SetToImap();
regularEmail.Send();

var reallySlowEmail = new Email();
reallySlowEmail.Method = ViaSnailMail;

public void ViaSnailMail(string title, string message) {...}

( !). , , , lambdas - , .

+5

, , , , .

, - / . - get set. , (), , get/set, , "=" "==".

. (, ), . , ; (). , , , , .

, - . .

- , ? ?

DoSomeFunction(ref variablePointer) 

, . ( ), , ref. , , , () , .

" " - . ( ) - () , .

:

class myClass
{ 
     public List<delegate> eventHandlers = new  List<delegate>();
     public void someMethod()
     {
          //... do some work
          //... then call the events
          foreach(delegate d in eventHandlers)
          {
               // we have no idea what the method name is that the delegate
               // points to, but we dont need to know - the pointer to the 
               // function is stored as a delegate, so we just execute the 
               // delegate, which is a synonym for the function.
               d();
          }
      }
 }

 public class Program()
 {
      public static void Main()
      {
          myClass class1 = new myClass();
          // 'longhand' version of setting up a delegate callback
          class1.eventHandlers.Add(new delegate(eventHandlerFunction));
          // This call will cause the eventHandlerFunction below to be 
          // called
          class1.someMethod();
          // 'shorthand' way of setting up a delegate callback
          class1.eventHandlers.Add(() => eventHandlerFunction());
      }
      public static eventHandlerFunction()
      {
           Console.WriteLine("I have been called");
      }

, , , "ref" - - , , , , . , " " ( ) " ". , , , .

, .

+1

, , , .

, , , Email.Send(). : . , , - " " (), , . , , , .

, , , (DoMoreWork()). Email.Send() , , .

, , ( ) , , Email.Send(), , IEmail, IEmail (To, From, Subject, Body, Attachments, HTMLBody ..), / -.

, , CDONTS, - . , CDONTS , , , , HTML. , , . Email.Send() ( ). , , . , ...

0

- , , , ( ).

, , Click. EventHandler. void EventHandler(object sender, EventArgs e);. , , - , , EventHandler, , . .

LINQ .Select(...). IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector). Func<TSource, TResult> selector. , , source TResult.

, Lazy<T>. : public Lazy(Func<T> valueFactory). Lazy<T> , T , . -, , , , , , , , . Lazy<T> .., , T. T, Func<T> valueFactory, - Lazy<T> , , .

, , .

0
source

All Articles