Nen*_*nad 107 c# generics where type-constraints
让我举个例子:
我有一些通用的类/接口定义:
interface IGenericCar< T > {...}
我有另一个类/接口,我想与上面的类相关,例如:
interface IGarrage< TCar > : where TCar: IGenericCar< (**any type here**) > {...}
基本上,我希望我的通用IGarrage依赖于IGenericCar,无论是否,IGenericCar<int>或者IGenericCar<System.Color>因为我对该类型没有任何依赖性.
Jar*_*Par 137
通常有两种方法可以实现这一目标
选项1:向IGarrage添加另一个参数,重新释放应该传递给IGarrage约束的T
interface IGarrage<TCar,TOther> where TCar : IGenericCar<TOther> { ... }
Run Code Online (Sandbox Code Playgroud)
选项2:定义一个T非通用的基本接口,并限制该接口
interface IGenericCar { ... }
interface IGenericCar<T> : IGenericCar { ... }
interface IGarrage<TCar> where TCar : IGenericCar { ... }
Run Code Online (Sandbox Code Playgroud)
做以下事情是否有意义:
interface IGenericCar< T > {...}
interface IGarrage< TCar, TCarType >
where TCar: IGenericCar< TCarType > {...}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33400 次 |
| 最近记录: |