Share via


Como implementar eventos de interface (Guia de Programação em C#)

Um interface pode declarar um evento. O exemplo a seguir mostra como implementar eventos de interface em uma classe. Basicamente as regras são as mesmas ao implementar qualquer propriedade ou método de interface.

Para implementar eventos de interface em uma classe

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

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

Exemplo

O exemplo a seguir mostra como tratar da 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 de interface explícita para pelo menos um dos eventos. Quando você escreve uma implementação de interface explícita para um evento, você também deve escrever o add e remove acessadores de evento. Normalmente, eles são fornecidos pelo compilador, mas nesse caso o compilador não pode fornecer-lhes.

Ao fornecer seus próprios acessadores, você pode especificar se os dois eventos são representados pelo mesmo evento na sua classe, ou por eventos diferentes. Por exemplo, se os eventos devem ser gerados em horas diferentes, de acordo com as especificações de interface, você pode associar cada evento de uma implementação separada na sua classe. No exemplo a seguir, os assinantes determinam qual OnDraw evento receberão por projeção a referência de forma a qualquer 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 acionar eventos de classe base em classes derivadas (Guia de Programação em C#)

Referência

Eventos (Guia de Programação em C#)

Delegados (Guia de Programação em C#)

Implementação de interface explícita (Guia de Programação em C#)

Conceitos

Guia de Programação em C#