122

让我举个例子:

  1. 我有一些通用类/接口定义:

    interface IGenericCar< T > {...}

  2. 我有另一个类/接口,我想与上面的类相关,例如:

    interface IGarrage< TCar > : where TCar: IGenericCar< (**any type here**) > {...}

基本上,我希望我的通用 IGarrage 依赖于IGenericCar,无论它是IGenericCar<int>还是IGenericCar<System.Color>,因为我对该类型没有任何依赖关系。

4

2 回答 2

145

通常有两种方法可以实现这一点。

Option1:添加另一个参数来IGarrage表示T应该传递给IGenericCar<T>约束的参数:

interface IGarrage<TCar,TOther> where TCar : IGenericCar<TOther> { ... }

选项2:定义一个IGenericCar<T>非通用的基本接口并约束该接口

interface IGenericCar { ... }
interface IGenericCar<T> : IGenericCar { ... }
interface IGarrage<TCar> where TCar : IGenericCar { ... }
于 2009-10-08T23:50:52.027 回答
6

做类似的事情是否有意义:

interface IGenericCar< T > {...}
interface IGarrage< TCar, TCarType > 
    where TCar: IGenericCar< TCarType > {...}
于 2009-10-08T23:50:00.170 回答