Share via


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

O simples exemplo a seguir mostra a forma padrão para declarar os eventos na classe base para que eles também podem ser disparados de classes derivadas.Esse padrão é usado amplamente em classes Windows Forms no .NET Framework biblioteca de classes.

Quando você cria uma classe que pode ser usada sistema autônomo uma classe base para outras classes, você deve considerar o fato de que sistema autônomo eventos são um tipo especial de delegado que só pode ser chamado de dentro da classe declarada-los.Classes derivadas não podem chamar diretamente eventos declarados dentro da classe base.Embora, às vezes, é aconselhável um evento que só pode ser disparado pela classe base, na maioria das vezes, você deve ativar a classe derivada chamar eventos de classe base.Para fazer isso, você pode criar um método de chamada protegido na classe base que envolve o evento.Ligando ou substituindo chamar esse método, as classes derivadas podem chamar o evento indiretamente.

Observação:

Não declarar eventos virtual em uma classe base e substituí-los em uma classe derivada.O compilador translation from VPE for Csharp não controla esses corretamente em Microsoft Visual Studio 2008 e é imprevisível se um assinante para o evento derivado serão realmente ser assinar o evento da classe base.

Exemplo

namespace BaseClassEvents
{
    using System;
    using System.Collections.Generic;

    // Special EventArgs class to hold info about Shapes.
    public class ShapeEventArgs : EventArgs
    {
        private double newArea;

        public ShapeEventArgs(double d)
        {
            newArea = d;
        }
        public double NewArea
        {
            get { return newArea; }
        }
    }

    // Base class event publisher
    public abstract class Shape
    {
        protected double area;

        public double Area
        {
            get { return area; }
            set { area = value; }
        }
        // The event. Note that by using the generic EventHandler<T> event type
        // we do not need to declare a separate delegate type.
        public event EventHandler<ShapeEventArgs> ShapeChanged;

        public abstract void Draw();

        //The event-invoking method that derived classes can override.
        protected virtual void OnShapeChanged(ShapeEventArgs e)
        {
            // Make a temporary copy of the event to avoid possibility of
            // a race condition if the last subscriber unsubscribes
            // immediately after the null check and before the event is raised.
            EventHandler<ShapeEventArgs> handler = ShapeChanged;
            if (handler != null)
            {
                handler(this, e);
            }
        }
    }

    public class Circle : Shape
    {
        private double radius;
        public Circle(double d)
        {
            radius = d;
            area = 3.14 * radius;
        }
        public void Update(double d)
        {
            radius = d;
            area = 3.14 * radius;
            OnShapeChanged(new ShapeEventArgs(area));
        }
        protected override void OnShapeChanged(ShapeEventArgs e)
        {
            // Do any circle-specific processing here.

            // Call the base class event invocation method.
            base.OnShapeChanged(e);
        }
        public override void Draw()
        {
            Console.WriteLine("Drawing a circle");
        }
    }

    public class Rectangle : Shape
    {
        private double length;
        private double width;
        public Rectangle(double length, double width)
        {
            this.length = length;
            this.width = width;
            area = length * width;
        }
        public void Update(double length, double width)
        {
            this.length = length;
            this.width = width;
            area = length * width;
            OnShapeChanged(new ShapeEventArgs(area));
        }
        protected override void OnShapeChanged(ShapeEventArgs e)
        {
            // Do any rectangle-specific processing here.

            // Call the base class event invocation method.
            base.OnShapeChanged(e);
        }
        public override void Draw()
        {
            Console.WriteLine("Drawing a rectangle");
        }

    }

    // Represents the surface on which the shapes are drawn
    // Subscribes to shape events so that it knows
    // when to redraw a shape.
    public class ShapeContainer
    {
        List<Shape> _list;

        public ShapeContainer()
        {
            _list = new List<Shape>();
        }

        public void AddShape(Shape s)
        {
            _list.Add(s);
            // Subscribe to the base class event.
            s.ShapeChanged += HandleShapeChanged;
        }

        // ...Other methods to draw, resize, etc.

        private void HandleShapeChanged(object sender, ShapeEventArgs e)
        {
            Shape s = (Shape)sender;

            // Diagnostic message for demonstration purposes.
            Console.WriteLine("Received event. Shape area is now {0}", e.NewArea);

            // Redraw the shape here.
            s.Draw();
        }
    }

    class Test
    {

        static void Main(string[] args)
        {
            //Create the event publishers and subscriber
            Circle c1 = new Circle(54);
            Rectangle r1 = new Rectangle(12, 9);
            ShapeContainer sc = new ShapeContainer();

            // Add the shapes to the container.
            sc.AddShape(c1);
            sc.AddShape(r1);

            // Cause some events to be raised.
            c1.Update(57);
            r1.Update(7, 7);

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
}
/* Output:
        Received event. Shape area is now 178.98
        Drawing a circle
        Received event. Shape area is now 49
        Drawing a rectangle
 */

Consulte também

Conceitos

Guia de Programação C#

Referência

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

Representantes (guia de programação C#)

Modificadores de acesso (guia de programação C#)

Outros recursos

Criando Manipuladores de Eventos nos Formulários do Windows