我一直下的印象是,C#編譯器能夠推斷類型PARAMS的情況下,像以下:爲什麼這C#5.0泛型:參數類型推斷
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;
}
}
任何想法正在發生的事情,以及如何在這種情況下得到類型推理工作?
謝謝。
可能重複http://stackoverflow.com/questions/6630690/wh y-cant-nested-generic-types-beferred(不是完全相同的問題,但Eric Lippert的答案也適用於你的問題)。 – haim770