使用泛型类型中定义的类型
本文关键字:类型 定义 泛型类型 | 更新日期: 2023-09-27 18:01:21
为标题道歉-我真的想不出一个很好的方式来描述我的需求。
我希望能够定义一个泛型接口(或类,这无关紧要),其中Type参数提供可以从类访问的另一个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()
{
}
显然,上面的代码不编译,所以有一种方法来实现这种行为的泛型链?
首先,IFoo也需要是通用的
interface IFoo<TDependent>
{
TDependent DependentType { get; }
}
那么IMyGeneric需要有两个类型参数
interface IMyGeneric<TBar,TDependent> where TBar : IFoo<TDependent>
{
TBar ReturnSomeTBar();
TDependent ReturnSomeTypeOnTBar();
}
也许这让你更接近你所追求的解决方案。
TBar.DependentType
必须是TBar
的一部分,这不是你可以为泛型类型参数做约束的那种。
用2个类型参数代替如何?IMyGenertic<TBar, TFoo>
吗?可用的解决方案?