Why doesn't an interface work but an abstract class does with a generic class constraint?

后端 未结 2 639
礼貌的吻别
礼貌的吻别 2021-01-02 02:30

The code below shows a generic class with a type constraint (Pub). The class has an event that it can raise allowing us to pass a message to subscriber

2条回答
  •  难免孤独
    2021-01-02 03:19

    Replace IMsg with T

    public interface IMsg { }        // Doesn't work
    
    public class Msg : IMsg { }
    
    public class Pub where T : IMsg
    {
        public event Action notify;
    
        public void Subscribe(object subscriber)
        {
            IHandler implementer = subscriber as IHandler; // here
    
            if (implementer != null)
            {
                this.notify += implementer.NotifyEventHandler;
            }
        }
    }
    
    public interface IHandler where T : IMsg
    {
        void NotifyEventHandler(T data);
    }
    

提交回复
热议问题