2011-07-04 35 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