Share via


방법: 인터페이스 이벤트 구현(C# 프로그래밍 가이드)

업데이트: 2007년 11월

인터페이스에서는 이벤트를 선언할 수 있습니다. 다음 예제에서는 클래스에 인터페이스 이벤트를 구현하는 방법을 보여 줍니다. 기본적으로 규칙은 인터페이스 메서드나 속성을 구현할 때와 동일합니다.

클래스에 인터페이스 이벤트를 구현하려면

  • 클래스에 이벤트를 선언하고 이를 적절한 영역에서 호출합니다.

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

예제

다음 예제에서는 클래스가 두 개 이상의 인터페이스에서 상속되며 각 인터페이스에 동일한 이름의 이벤트가 있는 보다 덜 일반적인 경우를 처리하는 방법을 보여 줍니다. 이 경우 하나 이상의 이벤트에 대해 명시적으로 인터페이스를 구현해야 합니다. 이벤트에 대한 명시적 인터페이스 구현을 작성할 때는 add 및 remove 이벤트 접근자를 작성해야 합니다. 일반적으로 이러한 접근자는 컴파일러에서 제공되지만 이 경우에는 컴파일러에서 제공할 수 없습니다.

사용자 고유의 접근자를 제공하면 두 이벤트를 클래스의 동일한 이벤트가 나타낼지 각기 다른 이벤트가 나타낼지를 지정할 수 있습니다. 예를 들어, 인터페이스 사양에 따라 다른 시간에 이벤트를 발생시켜야 하는 경우에는 클래스에 있는 별도의 구현에 각 이벤트를 연결할 수 있습니다. 다음 예제에서는 구독자가 IShape 또는 IDrawingObject에 대한 모양 참조를 캐스팅하여 수신할 OnDraw 이벤트를 결정합니다.

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.
*/

참고 항목

작업

방법: 파생 클래스에서 기본 클래스 이벤트 발생(C# 프로그래밍 가이드)

개념

C# 프로그래밍 가이드

참조

이벤트(C# 프로그래밍 가이드)

대리자(C# 프로그래밍 가이드)

명시적 인터페이스 구현(C# 프로그래밍 가이드)