Why can't I put a delegate in an interface?

前端 未结 7 1028
清歌不尽
清歌不尽 2021-02-01 03:24

Why can\'t I add a delegate to my interface?

7条回答
  •  情话喂你
    2021-02-01 04:22

    An interface method can accept a delegate as a parameter, no issues. (Maybe I'm not seeing the problem?) But if the intention is to specify an outbound call in the interface, use an event.

    There are so many little details, it's a lot easier to just show some code instead of trying to describe it all in prose. (Sorry, even the code sample is a bit bloated...)

    namespace DelegatesAndEvents
    {
        public class MyEventArgs : EventArgs
        {
            public string Message { get; set; }
            public MyEventArgs(string message) { Message = message; }
        }
    
        delegate void TwoWayCallback(string message);
        delegate void TwoWayEventHandler(object sender, MyEventArgs eventArgs);
    
        interface ITwoWay
        {
            void CallThis(TwoWayCallback callback);
    
            void Trigger(string message);
            event TwoWayEventHandler TwoWayEvent;
        }
    
        class Talkative : ITwoWay
        {
            public void CallThis(TwoWayCallback callback)
            {
                callback("Delegate invoked.");
            }
    
            public void Trigger(string message)
            {
                TwoWayEvent.Invoke(this, new MyEventArgs(message));
            }
    
            public event TwoWayEventHandler TwoWayEvent;
        }
    
        class Program
        {
            public static void MyCallback(string message)
            {
                Console.WriteLine(message);
            }
    
            public static void OnMyEvent(object sender, MyEventArgs eventArgs)
            {
                Console.WriteLine(eventArgs.Message);
            }
    
            static void Main(string[] args)
            {
                Talkative talkative = new Talkative();
    
                talkative.CallThis(MyCallback);
    
                talkative.TwoWayEvent += new TwoWayEventHandler(OnMyEvent);
                talkative.Trigger("Event fired with this message.");
    
                Console.ReadKey();
            }
        }
    }
    

提交回复
热议问题