Procedura: implementare gli eventi di interfaccia (Guida per programmatori C#)

Un'interfaccia può dichiarare un evento.Nell'esempio seguente viene illustrato come implementare eventi di interfaccia in una classe.Le regole sono le stesse utilizzate per l'implementazione di qualsiasi metodo o proprietà di interfaccia.

Per implementare eventi di interfaccia in una classe

  • Dichiarare l'evento nella classe e quindi richiamarlo nelle aree appropriate.

    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);
                }
            }
        }
    
    }
    

Esempio

Nell'esempio seguente viene illustrato come gestire la situazione meno comune in cui la classe eredita da due o più interfacce e a ogni interfaccia è associato un evento con lo stesso nome.In questo caso, è necessario fornire un'implementazione di interfaccia esplicita per almeno uno degli eventi.Quando si scrive un'implementazione di interfaccia esplicita per un evento, è anche necessario scrivere le funzioni di accesso agli eventi add e remove.In genere queste funzioni sono fornite dal compilatore, ma in questo caso il compilatore non è in grado di farlo.

Fornendo funzioni di accesso personalizzate, è possibile specificare se i due eventi sono rappresentati dallo stesso evento nella classe, o da eventi diversi.Ad esempio, se gli eventi devono essere generati in momenti diversi secondo le specifiche dell'interfaccia, è possibile associare ogni evento a un'implementazione separata nella classe.Nell'esempio seguente i sottoscrittori determinano l'evento OnDraw che riceveranno eseguendo il cast del riferimento della forma su IShape o 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.
*/

Vedere anche

Attività

Procedura: generare eventi della classe base in classi derivate (Guida per programmatori C#)

Riferimenti

Eventi (Guida per programmatori C#)

Delegati (Guida per programmatori C#)

Implementazione esplicita dell'interfaccia (Guida per programmatori C#)

Concetti

Guida per programmatori C#