2

为什么这不起作用?!

    public interface IBus
    {
        void Subscribe<T>(ISubscribe<T> subscriber) where T : class, IEvent;
        void Send<T>(IEvent @event) where T : class, IEvent;
    }

    class InMemoryEventBus : IBus
    {
        private readonly IDictionary<ISubscribe<IEvent>, Type> _subscribers;

        public InMemoryEventBus()
        {
            _subscribers= new Dictionary<ISubscribe<IEvent>, Type>();
        }

        public void Subscribe<T>(ISubscribe<T> subscriber) where T : class, IEvent
        {
            _subscribers.Add(subscriber, typeof(T));
        }

        public void Send<T>(IEvent @event) where T : class, IEvent
        {
            foreach (var subscriber in _subscribers.Where(subscriber => subscriber.Value == typeof(T)))
            {
                subscriber.Key.Handle(@event);
            }
        }
    }

    public interface IEvent
    {
        Guid EventId { get; set; }
    }

    public interface ISubscribe<T> where T : IEvent
    {
        void Handle(T @event);
    }

    public class StockLevelDroppedBellowMinimumLevelEvent : IEvent
    {
        public Guid EventId { get; set; }

        public string Message { get; set; }
    }

我得到:

cannot convert from 'IHandle<T>' to 'IHandle<IEvent>'
4

1 回答 1

4

编辑:实际上ISubscribe它需要是协变的 - 但现在我们可以看到 的声明ISubscribe,你不能让它协变 - 只有逆变。

一般来说,类型通常不是变体。例如, an ICollection<string>is not an ICollection<object>- 这是一项好工作,否则将编译:

ICollection<string> strings = new List<string>();
ICollection<object> objects = strings; // Fortunately this isn't valid
objects.Add(new Button()); // This should be fine of course...
string x = strings[0]; // But what would this do?!

在你的情况下,我相信你需要改变你的字典 - 你将能够保证ISubscribe在每种情况下都使用“正确”的类型。但是,您以一种非常奇怪的方式使用字典 - 您应该反转键和值类型,如下所示:

class InMemoryEventBus : IBus
{
    private readonly IDictionary<Type, object> _subscribers;

    public InMemoryEventBus()
    {
        _subscribers = new Dictionary<Type, object>();
    }

    public void Subscribe<T>(ISubscribe<T> subscriber) where T : IEvent
    {
        _subscribers.Add(typeof(T), subscriber);
    }

    public void Send<T>(IEvent @event) where T : class, IEvent
    {
        object value;
        if (_subscribers.TryGetValue(typeof(T), out value))
        {
             ISubscriber<T> subscriber = (ISubscriber<T>) value;
             subscriber.Handle(@event);
        }
    }
}
于 2012-08-09T16:42:47.777 回答