C#generic"where constraint"和"any generic type"定义?

Nen*_*nad 107 c# generics where type-constraints

让我举个例子:

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

    interface IGenericCar< T > {...}

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

    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)

  • 好的,但如果我需要在`IGarage <TCar>`中使用我的泛型类型`T`,我该怎么办?我在option2中看不到任何可能性.最好的解决方案是`IGarage <TCar>`通过分析类型`TCar`找到类型`T`. (6认同)
  • 对于后代,可以创建一个类型CAN,其类型参数为原始泛型类型,但仅在运行时使用反射,并且永远不会构造创建的类,因为如果没有完整定义,原始泛型类型参数永远不能自动构造ITS各自的类型参数.我没有看到这可能有用,除非在最外层类的超通用静态成员(即`IGarage <IGenericCar <?>>.TellMeAboutCarsInGeneral()`,这可能是设计不佳的结果) ,但我已经在我的修修补补中做到了,这是有可能的. (2认同)
  • @pt12lol:如果`IGarrage&lt;TCar&gt;` 实际上处理底层泛型类型(例如它处理所述类型的属性),那么它需要知道类型,这需要您指定类型,这是选项 1(唯一的那么可行的选择)。但是,如果`IGarrage&lt;TCar&gt;` 不直接处理底层泛型类型(所有`IGarrage&lt;TCar&gt;` 代码都与该底层类型无关),则选项2 有效。 (2认同)

sna*_*arf 6

做以下事情是否有意义:

interface IGenericCar< T > {...}
interface IGarrage< TCar, TCarType > 
    where TCar: IGenericCar< TCarType > {...}
Run Code Online (Sandbox Code Playgroud)