C# 泛型“where 约束”与“任何泛型类型”定义?
-
20-09-2019 - |
题
让我举个例子:
我有一些通用类/接口定义:
interface IGenericCar< T > {...}
我有另一个类/接口,我想与上面的类关联,例如:
interface IGarrage< TCar > : where TCar: IGenericCar< (**any type here**) > {...}
基本上,我希望我的通用 IGarrage 依赖于 IGenericCar
, ,无论是 IGenericCar<int>
或者 IGenericCar<System.Color>
, ,因为我对该类型没有任何依赖。
解决方案
通常有两种方法可以实现此目的。
选项1:添加另一个参数 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 { ... }
其他提示
这样做是否有意义:
interface IGenericCar< T > {...}
interface IGarrage< TCar, TCarType >
where TCar: IGenericCar< TCarType > {...}
不隶属于 StackOverflow