2014-09-12 111 views
2

說我有以下接口C#多級泛型接口

using System; 

public interface IInput 
{ 

} 

public interface IOutput<Shipper> where Shipper : IShipper 
{ 

} 

public interface IShipper 
{ 

} 


public interface IProvider<TInput, TOutput> 
    where TInput : IInput 
    where TOutput : IOutput<IShipper> 
{ 

} 

我能夠創建以下類別:

public class Input : IInput 
{ 

} 

public class Shipper : IShipper 
{ 

} 

public class Output : IOutput<Shipper> 
{ 

} 

我試過多種方法來創建實施IProvider帶班沒有運氣?

例:

public class Provider : IProvider<Input, Output> 
{ 

} 
Error: The type 'Output' cannot be used as type parameter 'TOutput' in the generic type or method 'IProvider<TInput,TOutput>'. There is no implicit reference conversion from 'Output' to 'IOutput<IShipper>' 

public class Provider : IProvider<Input, Output<IShipper>> 
{ 

} 
Error: The non-generic type 'Output' cannot be used with type arguments 

我怎樣才能做到這一點?

+0

要遵循慣例,'IOutput '的定義中的'發貨人'應該是'TShipper'。 – 2014-09-12 17:45:57

回答

4

您試圖將Shopper的泛型參數IOutput視爲協變。你需要明確指出,聲明接口時通用的說法是協變:

public interface IOutput<out Shipper> where Shipper : IShipper 
{ 

} 

(注意out關鍵字)。

然後將代碼編譯。

請注意,進行此更改後,您將不再能夠使用泛型類型參數Shipper作爲該接口的任何成員的參數;如果它將用於這樣一個莊園,那麼界面在概念上就不會是協變的。

您實際上可以簡化代碼以刪除一些與此問題無關的問題。這一切都歸結爲能做到以下幾點:

IOutput<Shipper> output = new Output(); 
IOutput<IShpper> = output; 

這種轉換隻有在有效IOutput是協變就其一般的參數。

+0

不能比這更好。 – CSharpie 2014-09-12 17:35:16

+0

我明白了。謝謝! – Baral 2014-09-12 17:40:21