具有继承的嵌套通用接口

时间:2013-12-05 07:34:57

标签: c# .net generics

定义:

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]类型。

1 个答案:

答案 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>>;