Cast to generic type in C#

前端 未结 13 914
野性不改
野性不改 2021-01-30 20:27

I have a Dictionary to map a certain type to a certain generic object for that type. For example:

typeof(LoginMessage) maps to MessageProcessor

        
13条回答
  •  太阳男子
    2021-01-30 21:29

        public delegate void MessageProcessor(T msg) where T : IExternalizable;
    
    
        virtual public void OnRecivedMessage(IExternalizable msg)
        {
            Type type = msg.GetType();
            ArrayList list = processors.Get(type);
            if (list != null)
            {
                object[] args = new object[]{msg};
                for (int i = list.Count - 1; i >= 0; --i)
                {
                    Delegate e = (Delegate)list[i];
                    e.Method.Invoke(e.Target, args);
                }
            }
        }
    

提交回复
热议问题