2010-03-15 17 views
17

Deseo crear eventos propios y enviarlos. Nunca he hecho esto antes en C#, solo en Flex ... Creo que debe haber muchas diferencias.Cómo enviar eventos en C#

¿Alguien me puede dar un buen ejemplo?

+1

WinForms, WebForms, ASP.NET MVC o WPF? – Oded

+1

un poco más de fondo? – Grzenio

+0

¡Gracias por todas las respuestas! Me ayudaron a todos juntos;) ¡Gracias de nuevo! –

Respuesta

43

Hay un patrón que se utiliza en todas las clases de la biblioteca. También se recomienda para sus propias clases, especialmente para el código de framework/library. Pero nadie lo detendrá cuando se desvíe u omita algunos pasos.

Aquí hay un esquema basado en el evento-delegado más simple, System.Eventhandler.

// The delegate type. This one is already defined in the library, in the System namespace 
// the `void (object, EventArgs)` signature is also the recommended pattern 
public delegate void Eventhandler(object sender, Eventargs args); 

// your publishing class 
class Foo 
{ 
    public event EventHandler Changed; // the Event 

    protected virtual void OnChanged() // the Trigger method, called to raise the event 
    { 
     // make a copy to be more thread-safe 
     EventHandler handler = Changed; 

     if (handler != null) 
     { 
      // invoke the subscribed event-handler(s) 
      handler(this, EventArgs.Empty); 
     } 
    } 

    // an example of raising the event 
    void SomeMethod() 
    { 
     if (...)  // on some condition 
     OnChanged(); // raise the event 
    } 
} 

Y cómo usarlo:

// your subscribing class 
class Bar 
{  
    public Bar() 
    { 
     Foo f = new Foo(); 
     f.Changed += Foo_Changed; // Subscribe, using the short notation 
    } 

    // the handler must conform to the signature 
    void Foo_Changed(object sender, EventArgs args) // the Handler (reacts) 
    { 
     // the things Bar has to do when Foo changes 
    } 
} 

Y cuando se tiene información para transmitir:

class MyEventArgs : EventArgs // guideline: derive from EventArgs 
{ 
    public string Info { get; set; } 
} 

class Foo 
{ 
    public event EventHandler<MyEventArgs> Changed; // the Event 
    ... 
    protected virtual void OnChanged(string info)  // the Trigger 
    { 
     EventHandler handler = Changed; // make a copy to be more thread-safe 
     if (handler != null) 
     { 
      var args = new MyEventArgs(){Info = info}; // this part will vary 
      handler(this, args); 
     } 
    } 
} 

class Bar 
{  
    void Foo_Changed(object sender, MyEventArgs args) // the Handler 
    { 
     string s = args.Info; 
     ... 
    } 
} 

actualización

Comenzando con C# 6 el código de llamada en el método 'disparador' se ha convertido en mucho más fácil, la prueba nula se puede acortar con el operador nulo condicional ?. sin hacer una copia, manteniendo hilo de seguridad:

protected virtual void OnChanged(string info) // the Trigger 
{ 
    var args = new MyEventArgs{Info = info}; // this part will vary 
    Changed?.Invoke(this, args); 
} 
+0

Supongo que puedo reemplazar los EventArgs, ¿con mi propia clase? –

+1

Sí, aunque usaría EventHandler donde T es el tipo de su evento args también conocido como ... evento público EventHandler MyEvent; – Sekhat

+1

También es un campo común.Práctica de NET que su clase EventArgs personalizada hereda de EventArgs – Sekhat

0

Mira en 'delegates'.

  • Definir un delegado
  • Utilice el tipo de delegado como campo/propiedad (añadiendo la palabra clave 'Evento')
  • Ahora está exponiendo a los eventos que los usuarios pueden enganchar en la " + = MyEventMethod; "

Espero que esto ayude,

3

delegados Eventos en C# de uso.

public static event EventHandler<EventArgs> myEvent; 

static void Main() 
{ 
    //add method to be called 
    myEvent += Handler; 

    //call all methods that have been added to the event 
    myEvent(this, EventArgs.Empty); 
} 

static void Handler(object sender, EventArgs args) 
{ 
    Console.WriteLine("Event Handled!"); 
} 
3

Usando el patrón típico de eventos .NET, y suponiendo que no necesita ningún argumento especial en su evento. Su patrón típico de evento y despacho se ve así.

public class MyClassWithEvents 
    { 
     public event EventHandler MyEvent; 

     protected void OnMyEvent(object sender, EventArgs eventArgs) 
     { 
      if (MyEvent != null) 
      { 
       MyEvent(sender, eventArgs); 
      } 
     } 

     public void TriggerMyEvent() 
     { 
      OnMyEvent(sender, eventArgs); 
     } 
    } 

Atar algo en el evento puede ser tan simple como:

public class Program 
{ 
    public static void Main(string[] args) 
    { 
     MyClassWithEvents obj = new MyClassWithEvents(); 

     obj.MyEvent += obj_myEvent; 
    } 

    private static void obj_myEvent(object sender, EventArgs e) 
    { 
     //Code called when my event is dispatched. 
    } 
} 

Tome un vistazo a los enlaces de this MSDN page

+0

y gracias por su ayuda también !! –