2013-03-01 69 views
0

我有兩個接口實現通用參數,鑄造接口與由類沒有通用參數

public interface IDocument<SegType> where SegType : ISegment 

public interface ISegment 

基本上,我想強制使每個實現IDocument類由一個的類型爲ISegment,使用這些類的人從不需要知道他們的類在內部使用哪種類型的ISegment

我再創建一個實現IDocument<SegType> where SegType : ISegment類:

public class MyDocument : IDocument<MySegment> 

和相應的MySegment

public class FffSegment : ISegment 

所有這一切編譯和作品一樣我也希望當我指定MyDocument作爲類型。爲什麼我不能隱式投射MyDocument的實例爲IDocument<Isegment>?當我嘗試行:

IDocument<ISegment> doc = new MyDocument(); 

我得到的錯誤

Cannot implicitly convert type 'MyDocument' to 'IDocument<ISegment>'. An explicit conversion exists (are you missing a cast?) 

但是,當我投它,它只是回來空。如果我將其更改爲:

IDocument<MySegment> doc = new MyDocument(); 

它的工作原理,當我改變類定義

public class MyDocument : IDocument<ISegment> 

我爲什麼不能強迫實現ISegment爲的IDocument的是執行特定類型的,因爲它呢?我想重複使用此代碼的不同類型的IDocumentISegment,也許某天某些實施IDocument將允許多種類型的ISegment,但MyDocument應限制這種行爲。我如何執行這些要求,但是仍然編寫足夠通用的代碼,以便將來可以重複使用?

回答

3

你需要進入合作和禁忌變異的污穢:

public interface IDocument<out SegType> where SegType : ISegment 
{} 

我覺得應該讓你比如現在編譯...

下面是一些閱讀材料:

+0

謝謝。這正是我需要的。那第一個msdn博客文章鏈接特別有趣,我想我也必須閱讀其他兩個。我應該注意到,我必須做出另一個小改變。 'IDocument'在IList 的方法上有一個返回值,但顯然'IList'不是協變的。 'IEnumerable'是,所以我改變它。從這個SO問題中想出來: http://stackoverflow.com/a/7416775/761590 – Drewmate 2013-03-01 22:10:46

+0

@Drewmate爲了什麼值得,我*不斷地*混淆了兩個... – JerKimball 2013-03-01 22:13:31

0

因爲IDocument<MySegment>不能直接投射到IDocument<ISegment>。如果可以,你可以這樣做:

IDocument<ISegment> doc1 = new IDocument<MySegment>; 
doc1.Add(new MyOtherSegment()); // invalid 

(假設IDocument<T>有一個Add(T newSegment)法)

需要很長的看看你的設計,並決定是否仿製藥是真的有必要,或者只是使用ISegmentIDocument是足夠。