2011-07-04 74 views
3

標題道歉 - 我真的想不出一個很好的方式來描述我的要求。使用類型定義在通用類型

我希望能夠定義一個通用的接口(或類,沒關係),從而Type參數提供另一個可以從類訪問的類型。希望這段代碼能夠解釋。

interface IFoo 
{ 
    TOtherType DependentType { get; } 
} 

interface IMyGeneric<TBar> where TBar : IFoo 
{ 
    TBar ReturnSomeTBar(); 
    TBar.DependentType ReturnSomeTypeOnTBar(); 
} 

因此,在這個例子中,我希望有一個類來實現IFoo(如Foo)和揭露另一種類型,DependentType(例如int),所以我可以用IMyGeneric<Foo>有方法:

public Foo ReturnSomeTBar() 
{ 
} 

public int ReturnSomeTypeOnTBar() 
{ 
} 

顯然,上面的代碼不會編譯,所以有沒有辦法實現這種通用鏈接行爲?

回答

2

首先,IFoo的需要是通用太

interface IFoo<TDependent> 
{ 
    TDependent DependentType { get; } 
} 

然後IMyGeneric需要有

interface IMyGeneric<TBar,TDependent> where TBar : IFoo<TDependent> 
{ 
    TBar ReturnSomeTBar(); 
    TDependent ReturnSomeTypeOnTBar(); 
} 

這也許讓你更接近的solutin你2型PARAMS;再後。

1

TBar.DependentType必須是TBar的一部分,這不是您可以對泛型類型參數進行約束的那種類型。

如何使用2個類型參數? IMyGenertic<TBar, TFoo>?可用的解決方法?

+0

事實上,2型參數是我考慮過的一種解決方法,但它不是我所需要的行爲,因爲這些類型將是獨立的。這將是一個可以接受的妥協 – RichK