繁体   English   中英

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

[英]C# generic "where constraint" with "any generic type" definition?

我举个例子:

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

    interface IGenericCar< T > {...}

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

    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 > {...}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM