小编典典

具有“任何泛型类型”定义的C#泛型“ where约束”?

c#

让我举个例子:

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

interface IGenericCar< T > {...}

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

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

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


阅读 698

收藏
2020-05-19

共1个答案

小编典典

通常有两种方法可以实现此目的。

选项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 { ... }
2020-05-19