Compartilhar via


Como: Implementar interface de eventos (guia de programação translation from VPE for Csharp)

An interface pode declarar um evento.O exemplo a seguir mostra como implementar a interface de eventos em uma classe.Basicamente sistema autônomo regras são iguais ao implementar qualquer propriedade ou método de interface.

Para implementar a interface de eventos em uma classe

  • Declare o evento na sua classe e, em seguida, chamá-la nas áreas apropriadas.

    public interface IDrawingObject
    {
        event EventHandler ShapeChanged;
    }
    public class MyEventArgs : EventArgs {…}
    public class Shape : IDrawingObject
    {
        event EventHandler ShapeChanged;
        void ChangeShape()
        {
            // Do something before the event…
            OnShapeChanged(new MyEventsArgs(…));
            // or do something after the event. 
        }
        protected virtual void OnShapeChanged(MyEventArgs e)
        {
            if(ShapeChanged != null)
            {
               ShapeChanged(this, e);
            }
        }
    }
    

Exemplo

O exemplo a seguir mostra como lidar com a situação menos comuns em que sua classe herda de duas ou mais interfaces e cada interface tem um evento com o mesmo nome.Nessa situação, você deve fornecer uma implementação explícita da interface para pelo menos um dos eventos.Quando você escreve uma implementação explícita da interface para um evento, você deve escrever o add e remove acessadores de evento. Normalmente essas são fornecidas pelo compilador, mas nesse caso o compilador não pode fornecer a eles.

Ao oferecer seus próprios acessadores, você pode especificar se os dois eventos são representados por mesmo evento na sua classe ou por eventos diferentes.Por exemplo, se os eventos devem ser gerados em horários diferentes para de acordo com as especificações de interface, você pode associar cada evento com uma implementação separada na sua classe.No exemplo a seguir, os assinantes determinam quais OnDraw eles receberão por converter a referência de forma a um evento um IShape ou um IDrawingObject.

namespace WrapTwoInterfaceEvents
{
    using System;

    public interface IDrawingObject
    {
        // Raise this event before drawing
        // the object.
        event EventHandler OnDraw;
    }
    public interface IShape
    {
        // Raise this event after drawing
        // the shape.
        event EventHandler OnDraw;
    }


    // Base class event publisher inherits two
    // interfaces, each with an OnDraw event
    public class Shape : IDrawingObject, IShape
    {
        // Create an event for each interface event
        event EventHandler PreDrawEvent;
        event EventHandler PostDrawEvent;

        object objectLock = new Object();

        // Explicit interface implementation required.
        // Associate IDrawingObject's event with
        // PreDrawEvent
        event EventHandler IDrawingObject.OnDraw
        {
            add
            {
                lock (objectLock)
                {
                    PreDrawEvent += value;
                }
            }
            remove
            {
                lock (objectLock)
                {
                    PreDrawEvent -= value;
                }
            }
        }
        // Explicit interface implementation required.
        // Associate IShape's event with
        // PostDrawEvent
        event EventHandler IShape.OnDraw
        {
            add 
            {
                lock (objectLock)
                {
                    PostDrawEvent += value;
                }
            }
            remove
            {
                lock (objectLock)
                {
                    PostDrawEvent -= value;
                }
            }


        }

        // For the sake of simplicity this one method
        // implements both interfaces. 
        public void Draw()
        {
            // Raise IDrawingObject's event before the object is drawn.
            EventHandler handler = PreDrawEvent;
            if (handler != null)
            {
                handler(this, new EventArgs());
            }
            Console.WriteLine("Drawing a shape.");

            // RaiseIShape's event after the object is drawn.
            handler = PostDrawEvent;
            if (handler != null)
            {
                handler(this, new EventArgs());
            }
        }
    }
    public class Subscriber1
    {
        // References the shape object as an IDrawingObject
        public Subscriber1(Shape shape)
        {
            IDrawingObject d = (IDrawingObject)shape;
            d.OnDraw += new EventHandler(d_OnDraw);
        }

        void d_OnDraw(object sender, EventArgs e)
        {
            Console.WriteLine("Sub1 receives the IDrawingObject event.");
        }
    }
    // References the shape object as an IShape
    public class Subscriber2
    {
        public Subscriber2(Shape shape)
        {
            IShape d = (IShape)shape;
            d.OnDraw += new EventHandler(d_OnDraw);
        }

        void d_OnDraw(object sender, EventArgs e)
        {
            Console.WriteLine("Sub2 receives the IShape event.");
        }
    }


    public class Program
    {
        static void Main(string[] args)
        {
            Shape shape = new Shape();
            Subscriber1 sub = new Subscriber1(shape);
            Subscriber2 sub2 = new Subscriber2(shape);
            shape.Draw();

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }

}
/* Output:
    Sub1 receives the IDrawingObject event.
    Drawing a shape.
    Sub2 receives the IShape event.
*/

Consulte também

Tarefas

Como: Usar um dicionário para armazenar instâncias de eventos (Guia de programação C#)

Conceitos

Guia de Programação C#

Referência

Eventos (Guia de programação do C#)

Representantes (guia de programação C#)

implementação explícita da interface (guia de programação translation from VPE for Csharp)