定义:
public interface IRecord { }
public interface IEvent<out T> { }
public interface IHandler<out T> { }
public class RecordA : IRecord { }
public class EventA : IEvent<RecordA> { }
public class HandlerA : IHandler<IEvent<IRecord>> { }
代码:
IHandler<EventA> h1 = new HandlerA() as IHandler<EventA>;
IHandler<IEvent<RecordA>> h2 = new HandlerA() as IHandler<IEvent<RecordA>>;
为什么h1和h2都会导致NULL?
根据[HandlerA]的定义,它应该能够处理任何IEvent [IRecord]类型。
答案 0 :(得分:0)
您应该将covariance更改为IHandler
界面中的contravariance,它会起作用:
public interface IHandler<in T> { }
//It works
var h1 = new HandlerA() as IHandler<EventA>;
var h2 = new HandlerA() as IHandler<IEvent<RecordA>>;