Udostępnij za pośrednictwem


Jak: Implementacja interfejsu zdarzenia (Podręcznik programowania C#)

Interfejsu można zadeklarować zdarzenia.Poniższy przykład pokazuje, jak zaimplementować interfejsu zdarzenia w klasie.Zasadniczo zasady są takie same, jak podczas implementowania dowolnego interfejsu metody lub właściwości.

Aby zaimplementować interfejsu zdarzenia w klasie

  • Zadeklarować zdarzenia w klasie, a następnie wywołać w odpowiednich dziedzinach.

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

Przykład

Poniższy przykład pokazuje, jak obsługiwać mniej wspólnego sytuacji, w którym klasa dziedziczy z dwóch lub więcej interfejsów i każdy interfejs ma zdarzenia o tej samej nazwie.W tej sytuacji należy dostarczyć w jawnej implementacji interfejsu dla co najmniej jednego zdarzenia.Podczas pisania w jawnej implementacji interfejsu zdarzenia musi także napisać add i remove akcesorów zdarzeń.Zwykle są one dostarczane przez kompilator, ale w tym przypadku kompilator nie może dostarczyć je.

Udzielając akcesorów własne, można określić, czy dwa zdarzenia są reprezentowane przez tego samego zdarzenia w klasie lub przez różnych zdarzeń.Na przykład jeśli zdarzenia powinien zostać podniesiony w różnym czasie, zgodnie ze specyfikacją interfejsu, można skojarzyć każdego zdarzenia z oddzielnych wdrożenia w klasie.W poniższym przykładzie abonentów określić, które OnDraw zdarzenie, które otrzymają przez rzutowanie odniesienia kształtu albo IShape lub 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.
*/

Zobacz też

Zadania

Jak: podnoszenie zdarzeń klasy podstawowej w klas pochodnych (Podręcznik programowania C#)

Informacje

Zdarzenia (Podręcznik programowania C#)

Pełnomocnicy (Podręcznik programowania C#)

Jawne implementacji interfejsu (Podręcznik programowania C#)

Koncepcje

Podręcznik programowania C#