簡體   English   中英

具有繼承的嵌套泛型接口

[英]Nested Generic Interfaces with Inheritance

定義:

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

您應該改變協方差逆變IHandler界面,它會工作:

public interface IHandler<in T> { }

//It works
var h1 = new HandlerA() as IHandler<EventA>;
var h2 = new HandlerA() as IHandler<IEvent<RecordA>>;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM