我一直认为 C# 编译器能够在以下情况下推断类型参数:
class Program
{
static void Main(string[] args)
{
IMessageBus messageBus = null;
//Here the compiler nags "type params for Publish cannot be inferred from the usage.. .."
messageBus.Publish(new CorrectorAdded(10));
}
}
public interface IEvent<out TPayload>
{
TPayload Payload { get; }
}
public abstract class EventBase<TPayload> : IEvent<TPayload>
{
public TPayload Payload { get; private set; }
protected EventBase(TPayload payload)
{
Payload = payload;
}
}
public interface IMessageBus
{
void Publish<TEvent, TPayload>(TEvent @event) where TEvent : IEvent<TPayload>;
IDisposable Subscribe<TEvent, TPayload>(Action<TPayload> listener) where TEvent : IEvent<TPayload>;
}
public class CorrectorAdded : EventBase<CorrectorAddedArgs>
{
public CorrectorAdded(CorrectorAddedArgs payload) : base(payload)
{
}
public CorrectorAdded(int correctorId) : this(new CorrectorAddedArgs(correctorId))
{
}
}
public class CorrectorAddedArgs
{
public int CorrectorId { get; private set; }
public CorrectorAddedArgs(int correctorId)
{
CorrectorId = correctorId;
}
}
关于为什么会发生这种情况以及如何让类型推断在这种情况下起作用的任何想法?
谢谢。