Код: Выделить всё
namespace Game {
public static class EventSystem {
public class EventBase { }
public interface IEventListener where TEvent : EventBase {
void OnEvent(TEvent ev);
}
private static Dictionary _subscriptions = new();
public static void AddListener(IEventListener listener) where TEvent : EventBase {
if (!_subscriptions.ContainsKey(typeof(TEvent))) {
_subscriptions.Add(typeof(TEvent), new());
}
var list = _subscriptions[typeof(TEvent)];
list.Add(listener);
}
public static void RemoveListener(IEventListener listener) where TEvent : EventBase {
if (_subscriptions.ContainsKey(typeof(TEvent))) {
var list = _subscriptions[typeof(TEvent)];
list.Remove(listener);
}
}
Код: Выделить всё
> Argument 1: cannot convert from
> 'Game.EventSystem.IEventListener' to
> 'Game.EventSystem.IEventListener'CS1503
Cast (
Код: Выделить всё
list.Add((IEventListener)listener);
Итак, если я правильно понимаю, IEventListener инвариантен к EventBase, хотя событие TEvent на самом деле является EventBase. Чего я не понимаю, так это "почему"?
PS. Я в курсе возможных утечек памяти, не будем это обсуждать) - просто хочу понять, что не так с параметрами обобщенного типа
Подробнее здесь: https://stackoverflow.com/questions/783 ... -interface