私は常に、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;
}
}
なぜこれが起こっているのか、その場合に型推論を機能させる方法についてのアイデアはありますか?
ありがとう。